compare oder compareTo Methoden schreiben ist doof. Und selbst wenn einem die IDE etwas austomatisch bastelt, sieht es oft furchtbar aus. Hier ein Lösungsvorschlag, zu dem ich gerne Eure Meinung hören würde. Zuerst die Hilfsklasse:
So sieht die Anwendung aus:
Man beachte, dass unnötige Vergleiche (wenn das Ergebnis bereits feststeht) nicht durchgeführt werden.
Java:
import java.util.Comparator;
public enum Compare {
LT(-1), EQ(0), GT(1);
public final int toInt;
private Compare(int toInt) {
this.toInt = toInt;
}
public Compare andThen(boolean v1, boolean v2) {
if(this == EQ) return v1 == v2 ? EQ : v1 ? GT : LT;
else return this;
}
public Compare andThen(char v1, char v2) {
if(this == EQ) return v1 < v2 ? LT : v1 > v2 ? GT : EQ;
else return this;
}
public Compare andThen(int v1, int v2) {
if(this == EQ) return v1 < v2 ? LT : v1 > v2 ? GT : EQ;
else return this;
}
//u.s.w. für Primitive und Arrays
public <T extends Comparable<? super T>> Compare andThen(T v1, T v2) {
return this == EQ ? fromInt(v1.compareTo(v2)) : this;
}
public <T> Compare andThen(T v1, T v2, Comparator<? super T> comparator) {
return this == EQ ? fromInt(comparator.compare(v1, v2)) : this;
}
private Compare fromInt(int compResult) {
return compResult < 0 ? LT : compResult > 0 ? GT : EQ;
}
}
So sieht die Anwendung aus:
Java:
import static somepackage.Compare.*;
class Person implements Comparable<Person> {
private String firstName;
private String lastName;
private Date birthDate;
...
public int compareTo(Person that) {
return EQ
.andThen(this.lastName, that.lastName)
.andThen(this.firstName, that.firstName)
.andThen(this.birthDate, that.birthDate)
.toInt;
}
}
Man beachte, dass unnötige Vergleiche (wenn das Ergebnis bereits feststeht) nicht durchgeführt werden.