Thursday, August 12, 2010

Java enum Is Evil

Before Java 1.5, I never really complained about the lack of enum keyword. Sure the old enum via class pattern was a bit verbose at first (N.B.: Java 1.5 enums can also be verbose once you start adding methods to them). But more importantly, you would often use the table lookup pattern in combination.

The problem with Java 1.5 enum is that it is not Object-Oriented. You can't extend an enum, you can't add an element in an existing enum. Many will say "but that's what enum is for, a static list of things". In my experience,  the list of things often changes with time, or needs to be extended at one point. Furthermore, most people (including me when I am very lazy) end up writing switch statements on enum values. Enum promotes bad programming practices.

Think twice about using enum, this is often not what you want.

3 comments :

  1. I tend to agree with you about enum's.

    I nearly always use an Interface instead :)

    ReplyDelete
  2. Extending an enum may be convenient, but goes against the Open/Closed principle. Imagine a Scope enum that contains only SESSION, APPLICATION and you decide to add CONVERSATION - you will be breaking existing third-party classes by doing so.

    If you have full access to all usage cases of the enum, you can modify the class itself (and then the Open/Closed principle doesn't apply, and inheritance is not needed).

    You still can use classes instead of enums if you need inheritance (spring does that, precisely, with Scope).

    ReplyDelete
  3. If you're needing to extend an enum, you're doing it wrong. An enum is more object oriented than a static final string/int, and that's the whole point. Enums can be unit tested, and based on what you're saying it would probably be good to include a switch statement in the unit test to remind you to update your existing code. But it's not a good idea to switch over an enum that might change in the future.

    Yes, an enum is not always what you want, but sometimes it is very helpful. The already pervasive bad practice of final strings is worse, so I'll take the lesser of two evils.

    ReplyDelete