The Pragmatic Craftsman :: Simplicity from complexity : by Stanley Kubasek ::

Java 5 Enums

Java 5 SE, in my opinion was a great release. While reading a blog post, Java 5 – The Gems and the Duds, the author gives thumbs up to the concurrency package, generics, CachedRowSet, and annotations; he gives thumbs down to autoboxing. And he’s not sure about varargs and enums. Very good post. I generally agree with the author. But…

I happen to like enums. I have used them several times already and they did a great job for me: made the code easier to understand and the code more robust (type safety). What are they good for?

I have used enums to encapsulate the different types. Pre Java 5, we used to have a lot of String constants defined. What that does it puts a lot of unrelated things together. It’s hard to see where each particular constant belongs to. There is also no type safety, as the constant can be substituted with any value.

No more. I can now define an enum. It nicely encloses related types. It gives me type safety. They make your code more readable. They make your comparisons easy — you can use == with confidence.

A simple example,enum DayOfWeek {MON(1), TUE(2), WED(3)… /* need to define a constructor in this case */ }

In code, you would no longer rely on integers 1-7 or strings for days, you would get a DayOfWeek param and you would be sure that you actually get the right value. You could also define a utility method inside the enum, getByDayNumber(…) and get the day that way.

In my opinion, a great addition.

ReferenceJava 5 – The Gems and the Duds, The Art and Craft of Great Software Architecture and Development blog

Enums, java.sun.com article

Related Posts

2 Responses to “Java 5 Enums”

  1. Dennis Doubleday says:

    The downside of enums is that they are not extensible. Otherwise, I like them.

  2. Yes, I agree, enums are not extensible, but if you have a fairly static set, they provide an excellent solution.

Favorite Quote

Topics

Tags

Archive

Currently Reading

Shelfari: Book reviews on your book blog

:: The Pragmatic Craftsman recommends

:: The Pragmatic Craftsman book reviews

Info

© 2001-2012 Stanley Kubasek About me :: Contact me

Me on Twitter

@leszekgruchala Good to hear it's fast. Looking to upgrade to IntelliJ 11 soon. - 2 days agoPutting related classes together is another way of looking at "structuring your code by feature." Makes your code more cohesive. Big + imho - 11 days agoplanetgeek.ch » Structure your code by feature - http://t.co/KcpMBKVg (via @sociablesite) #sociable - 11 days agoTell Congress: Don’t censor the web! http://t.co/ZEkgOAW7 - 18 days agoI must admit, I'm one of those developers that doesn't know too much about WeakReferences in Java. http://t.co/HjW7v9e0 Time to change that. - 19 days ago

»see more

Recent Entries