Correct Java switch statement

Correct Java switch statement

When writing correct code, we should prefer the compiler to do the checks for us, instead of the runtime. While Java’s type system helps us a lot with writing correct code, it has its limitations.

Consider an enumeration.

public enum AllowedColor {
RED, BLUE, YELLOW
}

A switch statement would look like

switch(color) {
case RED:
System.out.println("it's red");
break;
case BLUE:
System.out.println("it's blue");
break;
case YELLOW:
System.out.println("it's yellow");
break;
}

This looks ok, but what happens when someone adds a new enum constant is that we have a silent failure. Compiler will not inform us that this case isn’t handled. So I prefer to add a default block where I just throw an IllegalStateException, to prevent people not handling their case.

That, however, will be correct only if null is not an allowed value. We know switch statements can’t have a case of null. So an if is required, and I prefer to to it just above the switch and handle it all in a separate method.

So the correct code would be:

if(null == color) {
System.out.println("color not specified");
return;
}

switch(color) {
case RED:
System.out.println("it's red");
break;
case BLUE:
System.out.println("it's blue");
break;
case YELLOW:
System.out.println("it's yellow");
break;
default:
throw new IllegalStateException("Unhandled color " + color);
}

Ofcourse, we don’t always want to handle all cases and this need not be an enum. Following this simple practice will help you keep this piece of code correct when other parts of the system change.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.