83 lines
1.7 KiB
Plaintext
83 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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 14 added support for switch expressions, which provide more succinct and less error-prone version of switch.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
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
|
|
|
|
[source,java]
|
|
----
|
|
int numLetters = switch (day) {
|
|
case MONDAY, FRIDAY, SUNDAY -> 6;
|
|
case TUESDAY -> 7;
|
|
case THURSDAY, SATURDAY -> 8;
|
|
case WEDNESDAY -> 9;
|
|
};
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use "switch" expression to set value of "variable".
|
|
|
|
Use "switch" expression to return value from method.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 28 Jan 2019, 15:21:02 Tibor Blenessy wrote:
|
|
https://openjdk.java.net/jeps/325
|
|
|
|
endif::env-github,rspecator-view[]
|