Search code examples
javapackagestructurecomparator

What is the best place to place a Comparator Class in Java


I'm trying to decide where is the best place to put my comparator class on a Java project.

public class CustomerSortingComparator implements Comparator<Customer>{
 @Override
    public int compare(Customer customer1, Customer customer2) { 
     //... my implementation
     }
}

In my project I have several packages:

com.test.dao
com.test.model
com.test.controller
com.test.service
com.test.util
.....

I was thinking to add it to the util package since I can't find a good reference that suggests where to put it.


Solution

  • It’s clearly opinion-based, so I am hurrying to air mine. :-)

    If your comparator is to be used in one place only, implement it where it is used. Inside the same class or at least in the same package. The design principle of high cohesion dictates that this is where it belongs. In particular because from Java 8 comparators can often be defined in one or very few lines of code, there is no point in putting it in its own class. Just declare it in the class or even inside the method using it:

        Comparator<Customer> customerSortingComparator = Comparator.comparing(Customer::getLastName)
                .thenComparing(Customer::getFirstName);
    

    If on the other side the comparator is foreseen to be used in more than one class in more than one package, declare it in the package holding the Customer class. Again, the principle of high cohesion will tell you that this is the place.

    Real life story: In the project I am working on they have put all the comparators that compare customers (for the sake of the example) into one class in a package separate from the Customer class and also separate from the classes using those comparators. It has given us a class with a non-existent cohesion and a lot of unnecessary coupling across packages. A very poor design.

    Link: Cohesion (computer science) on Wikipedia