diff --git a/rules/S6888/java/metadata.json b/rules/S6888/java/metadata.json index 9e90e3569b9..6e9e2ac6ccb 100644 --- a/rules/S6888/java/metadata.json +++ b/rules/S6888/java/metadata.json @@ -1,5 +1,5 @@ { - "title": "FIXME", + "title": "Don't test if the variable is null before a switch", "type": "CODE_SMELL", "status": "ready", "remediation": { @@ -7,8 +7,9 @@ "constantCost": "5min" }, "tags": [ + "java21" ], - "defaultSeverity": "Major", + "defaultSeverity": "MEDIUM", "ruleSpecification": "RSPEC-6888", "sqKey": "S6888", "scope": "All", @@ -16,9 +17,7 @@ "quickfix": "unknown", "code": { "impacts": { - "MAINTAINABILITY": "HIGH", - "RELIABILITY": "MEDIUM", - "SECURITY": "LOW" + "MAINTAINABILITY": "MEDIUM" }, "attribute": "CONVENTIONAL" } diff --git a/rules/S6888/java/rule.adoc b/rules/S6888/java/rule.adoc index 4bd440f87a8..96e599b076e 100644 --- a/rules/S6888/java/rule.adoc +++ b/rules/S6888/java/rule.adoc @@ -1,44 +1,47 @@ -FIXME: add a description +Don't test if the variable is null before a switch -// If you want to factorize the description uncomment the following line and create the file. -//include::../description.adoc[] == Why is this an issue? -FIXME: remove the unused optional headers (that are commented out) +Since Java 21, can accept null values. Thus, it not necessary anymore to check if a variable is null before matching it and should even be avoided, as it lead to less readable code. -//=== What is the potential impact? == How to fix it -//== How to fix it in FRAMEWORK NAME + +Move the null check inside the switch statement. === Code examples ==== Noncompliant code example -[source,text,diff-id=1,diff-type=noncompliant] +[source,java,diff-id=1,diff-type=noncompliant] ---- -FIXME +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,text,diff-id=1,diff-type=compliant] +[source,java,diff-id=1,diff-type=compliant] ---- -FIXME +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"); + } +} ---- -//=== How does this work? - -//=== Pitfalls - -//=== Going the extra mile -//== Resources -//=== Documentation -//=== Articles & blog posts -//=== Conference presentations -//=== Standards -//=== External coding guidelines -//=== Benchmarks +== Resources +* https://openjdk.org/jeps/441[Pattern Matching for Switch]