Sunday, May 4, 2008

Beautiful enums

Whatever complaints you may have against java, I think you have to grant that at least enums are a thing of beauty. Consider this code line:

Collections.sort(myChildren, Child.Order.ByAge.descending());

The best part is that this started to appear as a side effect of another rational structuring of code, creating a synergy effect of two positive drives together. This kind of synergy always appeals to my aesthetic sense. Here's the Child class:

public final class Child {
private final Integer age;
private final String name;
...
public static enum Order implements Comparator {
ByAge() {
public int compare(Child lhs, Child rhs) {
return lhs.age.compareTo(rhs.age);
}
},
ByName() {
public int compare(Child lhs, Child rhs) {
// TODO: Should really use a collator.
return lhs.name.compareTo(rhs.name);
}
};

public abstract int compare(Child lhs, Child rhs);

public Comparator ascending() {
return this;
}

public Comparator descending() {
return Collections.reverseOrder(this);
}
}
}

Lovely! Other examples of the synergy effect I've seen recently are my earlier posted thread safe state pattern and this blog entry. In both those cases the synergy was better code structure and better performance.