57 lines
1.2 KiB
Plaintext
57 lines
1.2 KiB
Plaintext
Many existing switch statements are essentially simulations of switch expressions, where each arm either assigns to a common target variable or returns a value. Expressing this as a statement is roundabout, repetitive, and error-prone.
|
|
|
|
|
|
Java 12 added support for switch expressions, which provide more succinct and less error-prone version of switch.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
void day_of_week(DoW day) {
|
|
int numLetters;
|
|
switch (day) { // Noncompliant
|
|
case MONDAY:
|
|
case FRIDAY:
|
|
case SUNDAY:
|
|
numLetters = 6;
|
|
break;
|
|
case TUESDAY:
|
|
numLetters = 7;
|
|
break;
|
|
case THURSDAY:
|
|
case SATURDAY:
|
|
numLetters = 8;
|
|
break;
|
|
case WEDNESDAY:
|
|
numLetters = 9;
|
|
break;
|
|
default:
|
|
throw new IllegalStateException("Wat: " + day);
|
|
}
|
|
}
|
|
|
|
int return_switch(int x) {
|
|
switch (x) { // Noncompliant
|
|
case 1:
|
|
return 1;
|
|
case 2:
|
|
return 2;
|
|
default:
|
|
throw new IllegalStateException();
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
int numLetters = switch (day) {
|
|
case MONDAY, FRIDAY, SUNDAY -> 6;
|
|
case TUESDAY -> 7;
|
|
case THURSDAY, SATURDAY -> 8;
|
|
case WEDNESDAY -> 9;
|
|
};
|
|
----
|
|
|