May 15, 2005

Forget public static final String, Enums are here!

I mentioned in an earlier post that I'd post some examples on J2SE 5.0 real world usage. It's taken awhile, but for some time now, I've been using the latest Java in two separate projects. While not strictly meant for this purpose, Enums are very handy for avoiding typos in repetitive public static final String SOMESTRINGCONSTANT clauses. Instead of doing this, you could do an Enum of it, and never need to type in an actual string value. Since Enum is really a special class, you can just use toString() instead, i.e. define Enum SOMESTRING {value}, and in code, use as SOMESTRING.value.toString();

This has two benefits: You avoid writing the same or almost the same string twice and (public static final String NODENAME_TOYS = "toys";) and Enums can be checked compile time, so it's not possible to make a spelling mistake in the value of your constant.

A common case where you can use this pattern is when parsing XML. While you can and should have a schema for your XML format, your application logic still needs to understand the XML tree and process different nodes differently. So instead of making the nodenames constants, you could define an Enum for them. For example:
public Enum ToysAllowedNodes{Car, Ball, Scooter, Figures} and then use ToysAllowedNodes.values array to iterate over the nodes for node-specific processing.

Posted by thoughts at May 15, 2005 04:52 PM | TrackBack
Comments
Post a comment









Remember personal info?