The Pragmatic Craftsman         :: Simplicity from complexity :: | About Me |

You are here: The Pragmatic Craftsman > Java

Go to: « Read Books | Threads in Java »

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.

Reference
Java 5 - The Gems and the Duds, The Art and Craft of Great Software Architecture and Development blog

Enums, java.sun.com article


Comments

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

· November 21, 2006 · comment by Dennis Doubleday


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

· November 22, 2006 · comment by Stanley Kubasek


Post a comment









Remember personal info?







Go to:
   « previous entry: Read Books
   » next entry: Threads in Java

Random Quote

Search

 

Topics

Architecture & Design :12
Better Coder :29
Books :43
Books Recommended :18
Buzzwords :5
Career :25
Craftsmanship :15
Java :15
Quotes :25
Recommended :9
Software Engineering :3
Uncategorized :33
Web Development :1

Archive

May 2008 (1)
April 2008 (2)
March 2008 (1)
February 2008 (1)
January 2008 (2)
November 2007 (1)
October 2007 (3)
August 2007 (3)

...since January 2002

Currently Reading


:: See list of books I finished reading

Info

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