
Andy Pemberton is a Sun Certified Enterprise Architect and Senior Manager. Andy is an open source enthusiast with a depth of experience in WCM, Portal, JavaEE, and .NET environments.
Sep 01 2009
While many languages have enumerations built into the syntax, Sun didn't add the construct to Java until Java 5. After tooling around with enums a bit (blog entries forthcoming), I got to thinking... What makes an Enumeration? How constant is a constant? Maybe it's the philosophy major in me, but these are questions worth answering (or at least pondering aimlessly).
No matter how you slice it, enums in Java have the downside of requiring recompilation to add additional values, so my aim here is to answer the question: when should you choose to use an enumeration?
The java.sun.com website describes Enumerations as "a type whose fields consist of a fixed set of constants"; they go on to provide ideal examples of enumerations: days of the week, compass directions, and the planets in the solar system.
Wait a minute... didn't I read something about this recently? Yeah that's right; there are only 8 planets in the Solar system (after Pluto got demoted thanks to Neil deGrasse Tyson). So it turns out Sun's example enumeration is a little less constant than they thought - this is telling.
Anyone who's been developing software for a while knows that the idea of a constant is a myth. Requirements change. Ideas change. Objectives change... Planets change.
As is the case with many of the hard questions in software architecture, the decision to use an enumeration is not an easy one and is relative to your needs and your application.
Here are some questions to ask yourself in making a decision:
Question 3 is particularly helpful in deciding when to use an enumeration. If you must reference the values of a constant type in other compiled business logic, enumerations are a very compelling approach - they offer the most type-safety and concise code.
Regardless, the best I can do is offering a working heuristic:
use an enumeration if the constant values have a low enough frequency of change that redeploying your application is sufficient to update values.
The good news is, modern software methodologies (eg: Agile) tend to embrace change - through frequent releases and iterations pushing toward working code. These approaches are very helpful in leveraging enumerations, as there is a more open stance to change and less fear for refactoring and recompiling code.