A while ago I started my own initative to jump onto the Java5 train and use more and more features of the platform. In the past I had been forced by customers still using Java 1.4 to stick to it. I feel slowly now Java5 seems to drip in!
A few days ago I did some coaching on JSF and JPA and created a prototype to show to my trainee. I had the task of creating a JSf form that would allow to select from a select box a know set of values. On submission of the form each of the select box states should trigger a different action. Traditionally one would handle this with a stupid
if then else if... cascade.
With Java5 enums this can be done much simpler and easier to extend (for additional states).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
So this was the part of defining the possible states and the operations associated with each of the states. Now we need to convert the form input (from the select box), which is a simple string, into a enum.
Pretty compact - isn’t it, and any time you need a new state you just add it to the enum type along with your operation. It is even possible to enumerate all of the enum states - the enum type provides a static method
values() - to populate a select box in the user interface.
So when should you use enums? Any time you need a fixed set of constants. That includes natural enumerated types as well as other sets where you know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, and the like. It is not necessary that the set of constants in an enum type stay fixed for all time. The feature was specifically designed to allow for binary compatible evolution of enum types.