How to ensure completeness in an enum switch at compile time?
I don't know about the standard Java compiler, but the Eclipse compiler can certainly be configured to warn about this. Go to Window->Preferences->Java->Compiler->Errors/Warnings/Enum type constant not covered on switch.
Another solution uses the functional approach. You just need to declare the enum class according with next template:
public enum Direction {
UNKNOWN,
FORWARD,
BACKWARD;
public interface SwitchResult {
public void UNKNOWN();
public void FORWARD();
public void BACKWARD();
}
public void switchValue(SwitchResult result) {
switch (this) {
case UNKNOWN:
result.UNKNOWN();
break;
case FORWARD:
result.FORWARD();
break;
case BACKWARD:
result.BACKWARD();
break;
}
}
}
If you try to use this without one enumeration constant at least, you will get the compilation error:
getDirection().switchValue(new Direction.SwitchResult() {
public void UNKNOWN() { /* */ }
public void FORWARD() { /* */ }
// public void BACKWARD() { /* */ } // <- Compilation error if missing
});
In Effective Java, Joshua Bloch recommends creating an abstract method which would be implemented for each constant. For example:
enum Color {
RED { public String getName() {return "Red";} },
GREEN { public String getName() {return "Green";} },
BLUE { public String getName() {return "Blue";} };
public abstract String getName();
}
This would function as a safer switch, forcing you to implement the method if you add a new constant.
EDIT: To clear up some confusion, here's the equivalent using a regular switch
:
enum Color {
RED, GREEN, BLUE;
public String getName() {
switch(this) {
case RED: return "Red";
case GREEN: return "Green";
case BLUE: return "Blue";
default: return null;
}
}
}