Thursday, February 7, 2008

Java Enums

Everyone loves the open-ended interview question:

"So, tell me about java enums."

This is a good question for a reasonably well vetted candidate. Obviously, you don't want to ask any questions that result in a blank stare but if you've taken your candidate through a take home test with actual code in it, these sort of questions can lead to a great deal of fruitful conversation.

Enums are neat, and to tell you the truth, I hadn't really thought much about them until I asked a friend to walk my through some of the finer points of an Amazon job interview.

The most important thing about them (to my mind) is that they are a clean replacement for static final int

So you can replace this:

public static final int BLUE = 15;

public void setColor(int color) {
//do some stuff...
}

which will happily let you pass any integer into the set color method even if it isn't something that you've defined as a color.

with something like below:


public enum Color {
RED, PURPLE, GREEN
}

public void setColor(Color color) {
//do some stuff...
}


which will only let you pass something that you've described in the enum.

Even better if you call toString() on that int named BLUE above, you'll get "15". Call it on the enum Color.RED and you'll get "RED". That will certainly make for some much better debug messages.

What else? Well you can add methods:


public enum Color {
RED("#FF0000"),
PURPLE("#FF00FF"),
GREEN("#00FF00");
public String cHexValue;
private Color(String hexValue) {
cHexValue = hexValue;
}
public String getHex() {
return cHexValue;
}
}
...

System.out.println("What color is Red? " + Color.RED.getHex());


I can think of situations where that would make sense, but honestly, if I needed something like a Color object that had some properties, I'd likely create an actual java class and give it the properties that it needed and back its color labels with an internal enum. Maybe someone can give me a reason why that would be a bad idea in the comments?