user7086932 user7086932 - 1 month ago 8
Java Question

Is this a correct way to use Enum?

So I have a field called

optionType
and I want it to be able to take on 4 different integer values corresponding to certain options. For example optionType = 0 means the user wants to handle something a certain way, optionType = 1 means another way, etc.

But numbers by themselves are meaningless so I wanted to define constants instead in the class.

public class MyClass {
public static final int OPTION_TYPE_DO_THIS = 0;
public static final int OPTION_TYPE_DO_THAT = 1;
public static final int OPTION_TYPE_DO_SOMETHING_ELSE = 2;
public static final int OPTION_TYPE_DO_COOL_THING = 3;
private int optionType;

....


Is it considered normal to define all the constants out like that or is it better to use an enum like

public enum OPTION_TYPE {DO_THIS, DO_THAT, DO_SOMETHING_ELSE, DO_COOL_THING};


Or am I supposed to be using Enum instead somehow?

Answer

The key point is more on "how will that information be used at runtime". You see, if you starting thinking about writing code such as

switch(someEnum) {
  case DO_THIS: ...
  case DO_THAT:

... then you are already going into the wrong direction!

The point is: very often think that enums (or their even-more-low-level numeric constant cousins) are a good way to express such designs.

But that actually leads to quite some problems. Very often, the better, "more OO" way of thing is to use some abstract base class with specific subclasses; in other words: polymorphism!

Edit: just to make that more clear ... a "single" switch over an enum isn't really a problem. But far too often, people end up with many many places in code where they switch over their enums. And all of those places might need updates when you create additional enum constants. A coworker of mine calls that the "enum trap".

Comments