vendredi 15 janvier 2016

ComperatorFactory using static methods or each in its own class?

I was thinking of implementing multiple Comperators. Now I am not sure about how to do this in a most favourable way, i.e. still having the ability to do dependency injection.

Method 1: One class is one comparator (as seen in this answer):

// file LexicographicComparator.java
class LexicographicComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.name.compareToIgnoreCase(b.name);
    }
}

// file AgeComparator.java
class AgeComparator implements Comparator<Person> {
    @Override
    public int compare(Person a, Person b) {
        return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
    }
}

Method 2: Now it would surely be possible to do sth like this:

class PersonComperatorFactory {
    public static Comparator<Person> getAgeComparator() {
        return new Comparator<Person>() {
            @Override
            public int compare(Person a, Person b) {
                return a.age < b.age ? -1 : a.age == b.age ? 0 : 1;
            }
        }
    }

    public static Comparator<Person> getLexicographicComparator() {
        return new Comparator<Person>() {
            @Override
            public int compare(Person a, Person b) {
                return a.name.compareToIgnoreCase(b.name);
            }
        }
    }
}

The second method is surely less cluttering your packages (put it to the .domain package or .util package? Or create a new .domain.comperators package?). But is this a good idea at all? I mean, does this have any benefits besides less files? What about code reusage, or DependencyInjection - may it have drawbacks I am yet unable to see?

I'd like this to be not a "chose your favourite"-question, but there may be many good reasons why to use one or the other.

Thank you very much in advance.

PS: In which package would you put this (this is probably a personal choice)? But this is only a side-question suitable for a comment.

Aucun commentaire:

Enregistrer un commentaire