switch
statements are useful when there are many different cases depending on the value of the same expression. For just one or two
cases, however, the code will be more readable with if
statements.
In particular, if
statements are more suitable when the condition of the switch
is boolean.
This rule detects statements that could be simplified with a simple if / else
. That is when there is at most one case
,
not counting those that fall through to a default
.
The following code:
switch (variable) {
case 0:
doSomething();
break;
case 1:
case 2:
default:
doSomethingElse();
break;
}
Would be more readable that way:
if (variable == 0) {
doSomething();
} else {
doSomethingElse();
}
While the following snippets don’t trigger the rule because using if
would not improve their readability:
switch (variable) {
case 0:
case 1: // Would need a less readable check in an `if`
doSomething();
break;
}
switch (variable) {
case 0:
doSomething();
break;
case 1: // Would require introducing `else if`
doSomethingElse();
break;
}