Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions rules/S7473/java/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"title": "Unused variables in pattern matching should be replaced with unnamed variables",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "1min"
},
"tags": [
"unused",
"java22"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7473",
"sqKey": "S7473",
"scope": "All",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "targeted",
"code": {
"impacts": {
"MAINTAINABILITY": "MEDIUM"
},
"attribute": "CONVENTIONAL"
}
}
56 changes: 56 additions & 0 deletions rules/S7473/java/rule.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
== Why is this an issue?

Unused variables in pattern matching can make the code harder to understand and cause confusion.
This may lead to potential errors.

For example, the variable that is declared but not used, may be mistakenly assumed to have significance in the code.
This can lead to misunderstandings and make the code less readable.

== How to fix it

Replace unused variables with the unnamed variable `_`.
This will not change the behavior of the program, but it will reduce clutter and make the code clearer.

=== Exceptions

Unnamed variables are only available since Java 22, so the rule ignores projects configured with earlier
Java versions.

=== Code examples

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
public void foo(Ball ball){
switch (ball) {
case RedBall red -> process(ball); // Noncompliant, Use _ instead
case BlueBall blue -> process(ball); // Noncompliant, Use _ instead
case GreenBall green -> stopProcessing(); // Noncompliant, Use _ instead
}
if (r instanceof ColoredPoint(Point(int x, int y), Color c)) { // Noncompliant, Use _ instead
System.out.println("x: " + x);
}
}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
public void foo(Ball ball){
switch (ball) {
case RedBall _ -> process(ball); // Compliant, unused variable has been replaced with _
case BlueBall blue -> processColor(blue); // Compliant, variable blue is used
case GreenBall _ -> stopProcessing(); // Compliant
}
if (r instanceof ColoredPoint(Point(int x, _), _)) { // Compliant, no unused named variables
System.out.println("x: " + x);
}
}
----

== Resources

* https://openjdk.org/jeps/456[JEP 456: Unnamed Variables & Patterns]

2 changes: 2 additions & 0 deletions rules/S7473/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}