Tuesday, August 13, 2013

Enum: A safe translator


Many times we see an Enum declared like the following:


The Enum represents a value by Integer, and supplies a method (findByValue) to translate an int value to Enum value.

That is an error prone way to do that since every time you need to add/update/remove an Enum value you will need to remember to update 'findByValue' method

A possible fix

A better approach will be to do the following:


We keep a static HashMap that is statically initialized, and the 'findByValue' method is simpler. This version of the Enum makes sure any Enum value added/removed/updated will be automatically represented in the HashMap. i.e. no need for updating 'findByValue'

Generalizing the solution

First an interface class that defines a 'getValue' method:
And now a small class that basically wraps the HashMap and supplies an easy way for Enums to initialize:


And now wrapping all will give us the following:

No comments:

Post a Comment