rspec/rules/S6208/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

85 lines
1.5 KiB
Plaintext

== Why is this an issue?
In Java 14 there is a new way to write cases in Switch Statement and Expression when the same action should be performed for different cases. Instead of declaring multiples branches with the same action, you can combine all of them in a single case group, separated with commas. It will result in a more concise code and improved readability.
This rule reports an issue when multiple cases in a Switch can be grouped into a single comma-separated case.
=== Noncompliant code example
[source,java]
----
// Switch Expression
int i = switch (mode) {
case "a":
case "b":
yield 1;
default:
yield 3;
};
// Switch Statement
switch (mode) {
case "a":
case "b":
doSomething();
break;
default:
doSomethingElse();
}
----
=== Compliant solution
[source,java]
----
// Switch Expression
int i = switch (mode) {
case "a", "b":
yield 1;
default:
yield 3;
};
// Switch Statement
switch (mode) {
case "a", "b":
doSomething();
break;
default:
doSomethingElse();
}
// Or even better:
switch (mode) {
case "a", "b" -> doSomething();
default -> doSomethingElse();
}
----
== Resources
* https://openjdk.java.net/jeps/361[JEP 361: Switch Expressions]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Merge the previous cases into this one using comma-separated label.
=== Highlighting
* Primary: Last "case" keyword
* Secondaries: all previous cases
endif::env-github,rspecator-view[]