I see most developers using switch statements with breaks in each and every case
ID: 639403 • Letter: I
Question
I see most developers using switch statements with breaks in each and every case. Is this usage of switch statements inappropriate since a simple set of if-else statements would suffice?
Is it OK for me to think that the only reason for you to use a switch is because two or more cases are related, so you intentionally want some statements to "fall through"?
An example in which I think it's OK to use a switch is the case in which you want to update the schema of a database; so if you are updating from version 1 to version 4, you want to make sure the schema goes through versions 2 and 3 first:
private void updateDatabase(int oldVersion){
switch(oldVersion){
case 1:
updateToVersion2();
case 2:
updateToVersion3();
case 3:
updateToVersion4();
}
}
A NOT OK example of a switch is where I use it in a video game to move a character based on the button pressed. I would have to break each case so that when pressing LEFT the character doesn't move in all directions:
private void onButtonPressed(Button button){
switch(button){
case LEFT:
moveLeft();
break;
case RIGHT:
moveRight();
break;
case UP:
moveUp();
break;
case DOWN:
moveDown();
break;
}
}
Explanation / Answer
No, switch statements are not generally used wrong.
They are mostly used for their intended use: enumerating action alternatives for a smallish set of possible input values. It's more readable then a long if/else chain, compilers can emit very efficient code if the checked values are reasonably contiguous, and it's easier to write error-checking compilers that warn you when you forget an alternative. All this is well and good. (Using switch when inheritance and dynamic dispatch would be preferable is a common mistake among beginners who don't understand OOP very well yet, but that is a higher-level issue.)
However, switch is defined badly in most languages.
Since by far the most common use case is to do something different for each case, it's annoying and clutterful having to write break after each case that isn't a fall-through. The switch statement would work much better if break were the default after a case body, and you had to order fall-through via an explicit fallthrough keyword (unless two cases are directly adjacent). That would remove a lot of unnecessary lines, and many, many people wouldn't have made subtle errors by forgetting a break.
However, it's definitely too late now to do anything about that; C does it that way, and none of its descendants was brave enough to change anything about it, so for the time being, switch will probably stay as it is.