Java Ka Baby
Java Ka Baby

Reputation: 4920

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.

Upvotes: 6

Views: 1741

Answers (5)

Shahzeb
Shahzeb

Reputation: 4785

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.

Upvotes: 3

Alex
Alex

Reputation: 379

Yeah, if you use database or some external service and it's possible to sort there it's best way. But if you need to sort objects in your application it depends on your architecture. There are 2 variants. If you need sort only once - create anonymous class then you won't store reference on this object. If you need to make sort several times you can store it as static field of class or a non-static field.

Upvotes: 0

Jeff Foster
Jeff Foster

Reputation: 44706

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.

Upvotes: 4

Péter Török
Péter Török

Reputation: 116286

The general answer would be: put it where it is most required :-)

This depends a lot on your actual design and architecture. In general, either you can put it next to your user object, or into the layer which uses it most (or exclusively).

Upvotes: 0

Garbage
Garbage

Reputation: 1520

If you are using database, then best way is to sort it in query itself, using order by

Upvotes: 0

Related Questions