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?

3 comments:

Thomas Park said...

There are other benefits. Having a single static instance means you can do sane things like test for equality using "==". You get easy singleton-eque resource management. You can use a static import to shorten the usage of their namespace. But yes, there are obviously many cases where a PO-POJO would make more sense!

sadeysabia said...

Hotels near Foxwoods Casino - MapyRO
Hotels 서귀포 출장안마 1 - 12 of 61 — Looking for 세종특별자치 출장마사지 hotels near Foxwoods Casino in Washington State? We list over 2000 hotels 여주 출장안마 within a 25-minute drive, with information about 남양주 출장안마 top 제주도 출장안마 picks,

Anonymous said...

Well, with PlayOJO – there aren't any wagering requirements in any respect. That’s proper, simply eighty free spins and whatever you win, you get to keep. Or, if they're, the winnings are capped 1xbet at a certain amount|a specific amount|a sure quantity}.