Tuesday, November 22, 2005

There is a long history of the enum pattern in Java. What I have seen and used several times on different projects is a variant which we called the Extensible Enum Pattern. My fellow ex-ThoughtWorker, Andrew McCormick, first showed it to me.

Here is what I wrote the PCGen developer's list about this pattern when the question arose about processing program-defined and user-defined tokens together:

We have a set of conditions based on integer codes, some which we define themselves, others which are read from 3rd-party files and cannot all be known ahead of time.

Ok, so the object is immutable: there are no setters or editable fields. That is the first step towards being an enum. And so far there are no public way to create new ones. Lets open the class and add a factory method:

Now we have the other half of being an enum: no two instances of the same value are distinguishable. Whenever you try to create a new enum, if there is already an instance with the same code, you get back that instance rather than a new instance. (However, as the remark is just satellite data, not part of the identity of Status, you can see that you also get back the original remark.) Let's reinforce this message, and open the class again:

Lastly, let's open the class one final time to prepopulate it with our defined instances (be careful to initialize CODES before creating static instances or you'll get a NPE when trying to access the cache):

So that we got well-defined static instances for internal codes, and can generate new instances as required for external codes.

At bottom, I'll paste in a JDK5 version (generics, auto-boxing, annotations) along with some business methods. Note that the new JDK enum feature is not extensible. Otherwise, it is a thing of beauty, and in fact my next revision of this class for my client will model the JDK enum class more closely but retain the extensible property.