rspec/rules/S6916/java/rule.adoc
2024-02-27 15:25:30 +01:00

84 lines
2.4 KiB
Plaintext

== Why is this an issue?
Java 21 has introduced enhancements to switch statements and expressions, allowing them to operate on any type, not just specific ones, as in previous versions.
Furthermore, case labels have been upgraded to support patterns, providing an alternative to the previous restriction of only accepting constants.
[source,java]
----
// As of Java 21
String patternMatchSwitch(Object obj) {
return switch (obj) {
case String s -> String.format("String %s", s);
case Integer i -> String.format("int %d", i);
default -> obj.toString();
};
}
----
This allows to use the `when` keyword to specify a condition for a case label, also called a guarded case label.
[source,java]
----
String guardedCaseSwitch(Object obj) {
return switch (obj) {
case String s when s.length() > 0 -> String.format("String %s", s);
case Integer i when i > 0 -> String.format("int %d", i);
default -> obj.toString();
};
}
----
This syntax is more readable and less error-prone than using an if statement inside the case block and should be preferred.
This rule reports an issue when a single `if` statement is used inside a case block.
== How to fix it
Replace the `if` statement with a guarded case label.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
void testObject(Object response) {
switch (response) {
case String s -> {
if(s.length() > 80) { // Noncompliant; use the "when" keyword
System.out.println("This string is too long");
}
}
case Integer i -> {
if(i > 80) { // Noncompliant; use the "when" keyword
System.out.println("This integer is too big");
}
}
default -> System.out.println("Unknown type");
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
void testObject(Object response) {
switch (response) {
case String s when s.length() > 80 -> {
System.out.println("This string is too long");
}
case Integer i when i > 80 -> {
System.out.println("This integer is too big");
}
default -> System.out.println("Unknown type");
}
}
----
== Resources
=== Documentation
* Java Documentation - https://openjdk.org/jeps/441[Pattern Matching for switch]