We’re trying to make switch
statements simpler to understand at a glance.
Misunderstanding the control flow of a switch
block is a common source of
bugs.
switch
statements:case
and the case’s code. For example, case
HEARTS:
case
switch
block is large, just skimming each case
can be toilsomecase
. When
conditionally falling-through multiple case
s in a row is possible, the
number of potential control flows can grow rapidlyswitch
statementscase
and the case’s code. For example, case
HEARTS ->
switch
statement, you know at a glance that no cases
fall through. No control flow analysis neededcase
s (within a switch
)case A, B, C
) for
improved readabilityenum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}
private void foo(Suit suit) {
switch(suit) {
case HEARTS:
System.out.println("Red hearts");
case DIAMONDS:
System.out.println("Red diamonds");
case SPADES:
// Fall through
case DIAMONDS:
bar();
System.out.println("Black suit");
}
}
Which can be simplified into the following expression switch
:
enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}
private void foo(Suit suit) {
switch(suit) {
case HEARTS -> System.out.println("Red hearts");
case DIAMONDS -> System.out.println("Red diamonds");
case CLUBS, SPADES -> {
bar();
System.out.println("Black suit");
}
}
}
Here’s an example of a complex statement switch
with conditional fall-through
and complex control flows. How many potential execution paths can you spot?
enum Suit {HEARTS, CLUBS, SPADES, DIAMONDS}
private int foo(Suit suit){
switch(suit) {
case HEARTS:
if (bar()) {
break;
}
// Fall through
case CLUBS:
if (baz()) {
return 1;
} else if (baz2()) {
throw new AssertionError(...);
}
// Fall through
case SPADES:
// Fall through
case DIAMONDS:
return 0;
}
return -1;
}
Suppress false positives by adding the suppression annotation @SuppressWarnings("StatementSwitchToExpressionSwitch")
to the enclosing element.