64 lines
1.5 KiB
Plaintext
64 lines
1.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Java 21 introduces `case null` for `switch`. It is a more concise and readable way to handle nullability compared to an `if` statement before a `switch`.
|
|
[source,java]
|
|
----
|
|
switch (s) {
|
|
case null: /* code if null */
|
|
// ...
|
|
}
|
|
----
|
|
When the selector expression evaluates to null and the `case null` is present, switch statements don't throw a NullPointerException anymore.
|
|
It is not mandatory anymore to test for `null` before a `switch`, and it is more readable to use the `case null` form.
|
|
|
|
This rule identifies `if` statements that could be replaced by a more readable `case null` label.
|
|
[source,java]
|
|
----
|
|
if (s == null) {
|
|
/* code if null */
|
|
}
|
|
switch (s) {
|
|
// ...
|
|
}
|
|
----
|
|
|
|
== How to fix it
|
|
|
|
Move the null check inside the switch statement.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
static void f(String s) {
|
|
if (s == null) { // Noncompliant, we can move the null check in the switch statement.
|
|
System.out.println("Oops!");
|
|
return;
|
|
}
|
|
switch (s) {
|
|
case "Foo", "Bar" -> System.out.println("Great");
|
|
default -> System.out.println("Ok");
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
static void f(String s) {
|
|
switch (s) {
|
|
case null -> System.out.println("Oops!");
|
|
case "Foo", "Bar" -> System.out.println("Great");
|
|
default -> System.out.println("Ok");
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
|
|
== Resources
|
|
* https://openjdk.org/jeps/441[JEP 441: Pattern Matching for Switch]
|