I have a class that needs to be sortable in a couple of different ways, many of which break the equals()
contract, so I need to have a bunch of different Comparator
classes. The question I have is where should those classes live?
So that there is something concrete to use as an example namespace structure and to limit the question to package structure rather than file structure, lets assume the following namespaces:
app
domain
exception
hibernatemapping
mvc
propertyeditor
tags
persistence
hibernate
Domain classes live in the domain
namespace, and related exceptions and hibernate mapping files in exception
and hibernatemapping
respectively. persistence
holds DAO interfaces, with hibernate-based implementations in hibernate
. All of the MVC controllers live in mvc
, with specialized property editors (this is Spring MVC) in propertyeditor
and classes that back custom tags in tags
.
My gut says that Comparators
should live under the domain
namespace, perhaps in domain.comparator
, but I'm not sure.
Where would you put them and why?
Update: A number of people have suggested using a general Util开发者_C百科
package. When going that route, would you separate out the Util
classes by UI helpers vs. domain helpers? For example, if the domain needed to sort things for business logic reasons, but the UI needed additional sortings that the domain doesn't care about? Basically, would you tend to have a helper package per-layer?
As suggested, something like a util or a commons package would seem to make the most sense, though be sure you don't end up using that as a "goto" package if you don't know where to put something.
I'd also suggest looking into package by feature. In this cause, your compartor would just go with whatever corresponding feature its used with. Again, this is only a suggestion - you'll have to make the call for the best layout of your project.
I made a package called comparators
which is where I store mine.
I usually go with the following structure:
company
appname
model
util
dao
service
controller
In this type of structure a comparator would probably get dumped into the util package (if there were really a lot of comparators).
However, usually I find that comparators are used in exactly one place, and so I declare them inline where they're actually used, e.g.
public class SomeService {
public void someMethod(String id) {
List<ListType> list = dao.getSomeListById(id);
Collections.sort(list, new Comparator<ListType>() {
public compare(ListType a, ListType b) {
// ...
}
});
}
}
I suggest to create a package called "app.util" or "app.helper".
Conceptionally speaking, in Domain Driven Design this belongs in the infrastructure layer (http://www.infoq.com/articles/ddd-in-practice).
精彩评论