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

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

Info

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

Me on Twitter

»see more

Recent Entries