Beautiful enums

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.

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

     public Comparator ascending() {
        return this;

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

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s