Java enums are not constants
Every now and then I come across a person who points out that my enum values should be written as all upper case with underscores because in their minds an enum is a constant. I find myself disagreeing but haven't previously managed to explain why.
Historically in java we would use constants where we in other languages would have used an enum, so it doesn't seem unreasonable to consider enums to be constants. And yet they are not.
Consider the following code where we have tacos on a Friday as we like to do in Sweden:
After some time we get more and more influences from the US and we want to make tacos on Tuesday instead.
And now it should be evident: DayOfWeek.FRIDAY is not a constant, it is a hard-coded value. We could introduce a constant:
Now we can just reassign the constant TACO_DAY to the value DayOfWeek.TUESDAY.
In many other languages, it is possible to say that an enum has a value, e.g. DayOfWeek.FRIDAY might correspond to the integer value 5 and we can use FRIDAY or 5 as we see fit, but not so in java where FRIDAY is the value in the APIs and we are actively discouraged from thinking about its ordinal value in the list.
Consider also my previous post where instead of switching on an enum value to determine the code, we can actually implement the code in the enum.
Still think a java enum is a constant?
Historically in java we would use constants where we in other languages would have used an enum, so it doesn't seem unreasonable to consider enums to be constants. And yet they are not.
Consider the following code where we have tacos on a Friday as we like to do in Sweden:
class DinnerPlanner {
...
Menu createMenu() {
...
if (today.equals(DayOfWeek.FRIDAY)) {
menu.add("tacos");
}
...
}
...
void buyIngredients() {
...
if (today.equals(DayOfWeek.FRIDAY)) {
buy("taco shells", "tomatoes", ...);
}
...
}
...
void cook() {
...
if (today.equals(DayOfWeek.FRIDAY)) {
oven.put("taco shells");
fryingPan.put("mince").put("taco spices");
}
...
}
}
After some time we get more and more influences from the US and we want to make tacos on Tuesday instead.
And now it should be evident: DayOfWeek.FRIDAY is not a constant, it is a hard-coded value. We could introduce a constant:
static final DayOfWeek TACO_DAY = DayOfWeek.FRIDAY;
Now we can just reassign the constant TACO_DAY to the value DayOfWeek.TUESDAY.
In many other languages, it is possible to say that an enum has a value, e.g. DayOfWeek.FRIDAY might correspond to the integer value 5 and we can use FRIDAY or 5 as we see fit, but not so in java where FRIDAY is the value in the APIs and we are actively discouraged from thinking about its ordinal value in the list.
Consider also my previous post where instead of switching on an enum value to determine the code, we can actually implement the code in the enum.
Still think a java enum is a constant?
Comments