Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Place to Put a Comparator

I am sorry if I am asking something that has been answered already but I could not find a reference. My question is where is the best place to put a comparator which layer does it belong to.For example I need a list of User Objects sorted by users date of birth then surname and then first name.

like image 638
Java Ka Baby Avatar asked Jul 19 '11 08:07

Java Ka Baby


2 Answers

If the comparator is intrinsic to the object (e.g. it's the only way of ordering it that makes sense), then I would just implement Comparable on the object.

If the comparator is one of many (e.g. a Comparator instance), and only makes sense in a particular context, then I'd place the comparator class in that layer.

like image 168
Jeff Foster Avatar answered Sep 27 '22 23:09

Jeff Foster


In your case if would put it on the domain class and sort it in the dao during fetch meaning have two methods(or more based on Comaprision types) on dao one to just get a list of unsorted object e.g. getUsers() and one method for sorted list e.g getSortedUers(); ofcourse you can only have a sorted method but always calling a sort is an over head if no sort is required.

like image 32
Shahzeb Avatar answered Sep 28 '22 00:09

Shahzeb