diff --git a/rules/S7473/java/metadata.json b/rules/S7473/java/metadata.json new file mode 100644 index 00000000000..4352b8b18d9 --- /dev/null +++ b/rules/S7473/java/metadata.json @@ -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" + } +} diff --git a/rules/S7473/java/rule.adoc b/rules/S7473/java/rule.adoc new file mode 100644 index 00000000000..4288778233d --- /dev/null +++ b/rules/S7473/java/rule.adoc @@ -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] + diff --git a/rules/S7473/metadata.json b/rules/S7473/metadata.json new file mode 100644 index 00000000000..2c63c085104 --- /dev/null +++ b/rules/S7473/metadata.json @@ -0,0 +1,2 @@ +{ +}