Create rule S6888: "case null" should be preferred over "if" pre-condition (#3574)

This commit is contained in:
github-actions[bot] 2024-02-01 15:43:26 +01:00 committed by GitHub
parent 46b2c9eba6
commit fcf891083e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 89 additions and 0 deletions

View File

@ -0,0 +1,24 @@
{
"title": "\"case null\" should be preferred over \"if\" pre-condition",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"java21"
],
"defaultSeverity": "Minor",
"ruleSpecification": "RSPEC-6888",
"sqKey": "S6888",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
}

View File

@ -0,0 +1,63 @@
== 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]

View File

@ -0,0 +1,2 @@
{
}