DEV Community

Cover image for How not to design an Enum (Java)
Amir Maralani
Amir Maralani

Posted on

How not to design an Enum (Java)

Throughout the years, I've seen and created many Enums in Java. Some of them were very useful, some just avoided a bit of hard-code and a few bad ones.

This is an example of a very bad enum design. I'm not blaming anyone else, I was a contributor to this. But in my defense I was a newbie then. Let's take a look at it :

public enum EventStatusType {
     * event is processed {0 value in database}
     *  event is not processed {1 value in database}
     * event is now running {2 value in database}
     * event has failed {3 value in database}
Enter fullscreen mode Exit fullscreen mode

First of all, what's with the name? It's either a Status or a Type, which in this case it's a status, so EventStatus would be a better name.

Then we get to the JavaDocs. They are not explaining anything. Instead of explaining for example what does it mean that the event is in progress they are just a repetition of the values. Also, the mention of what they represent in the database is absolutely useless, redundant, and even incorrect. Useless and redundant because everyone working with enums and saving them by their ordinals in a database should know how they work. Incorrect because if we change the type used in our entity to String, we should not be forced to change the JavaDoc for the enum.

The other utterly annoying thing in this enum is its order. When watching the database to check the status of the events, you encounter some records with statuses of 0, 1, 2, and 3. Your intuition says the 0 is the base value, then the event status would move on to 1 and 2 (or 3). And you are wrong. The base value is 1, then you move to 2 and the final status is either 0 or 3. Very counter-intuitive.

Taking care of the mentioned issues with this code would improve the readability and ease of maintenance.

Do you have any more suggestions? Please share it with me.

Top comments (1)

alainvanhout profile image
Alain Van Hout

I would also suggest adding an explicit 'id' field instead of relying on the ordinal. Otherwise careless reordering (to make the order make more sense) would break the application.