Skip to content

Commit

Permalink
create rspec for rule "Don't test if the variable is null before a sw…
Browse files Browse the repository at this point in the history
…itch"
  • Loading branch information
erwan-serandour committed Jan 30, 2024
1 parent 245726d commit 3e9354b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 27 deletions.
9 changes: 4 additions & 5 deletions rules/S6888/java/metadata.json
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
{
"title": "FIXME",
"title": "Don't test if the variable is null before a switch",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"java21"
],
"defaultSeverity": "Major",
"defaultSeverity": "MEDIUM",
"ruleSpecification": "RSPEC-6888",
"sqKey": "S6888",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"MAINTAINABILITY": "HIGH",
"RELIABILITY": "MEDIUM",
"SECURITY": "LOW"
"MAINTAINABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
Expand Down
47 changes: 25 additions & 22 deletions rules/S6888/java/rule.adoc
Original file line number Diff line number Diff line change
@@ -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]

0 comments on commit 3e9354b

Please sign in to comment.