|
| 1 | +== Why is this an issue? |
| 2 | + |
| 3 | +Unused variables in pattern matching can make the code harder to understand and cause confusion. |
| 4 | +This may lead to potential errors. |
| 5 | + |
| 6 | +For example, the variable that is declared but not used, may be mistakenly assumed to have significance in the code. |
| 7 | +This can lead to misunderstandings and make the code less readable. |
| 8 | + |
| 9 | +== How to fix it |
| 10 | + |
| 11 | +Replace unused variables with the unnamed variable `_`. |
| 12 | +This will not change the behavior of the program, but it will reduce clutter and make the code clearer. |
| 13 | + |
| 14 | +=== Exceptions |
| 15 | + |
| 16 | +Unnamed variables are only available since Java 22, so the rule ignores projects configured with earlier |
| 17 | +Java versions. |
| 18 | + |
| 19 | +=== Code examples |
| 20 | + |
| 21 | +==== Noncompliant code example |
| 22 | + |
| 23 | +[source,java,diff-id=1,diff-type=noncompliant] |
| 24 | +---- |
| 25 | +public void foo(Ball ball){ |
| 26 | + switch (ball) { |
| 27 | + case RedBall red -> process(ball); // Noncompliant, Use _ instead |
| 28 | + case BlueBall blue -> process(ball); // Noncompliant, Use _ instead |
| 29 | + case GreenBall green -> stopProcessing(); // Noncompliant, Use _ instead |
| 30 | + } |
| 31 | + if (r instanceof ColoredPoint(Point(int x, int y), Color c)) { // Noncompliant, Use _ instead |
| 32 | + System.out.println("x: " + x); |
| 33 | + } |
| 34 | +} |
| 35 | +---- |
| 36 | + |
| 37 | +==== Compliant solution |
| 38 | + |
| 39 | +[source,java,diff-id=1,diff-type=compliant] |
| 40 | +---- |
| 41 | +public void foo(Ball ball){ |
| 42 | + switch (ball) { |
| 43 | + case RedBall _ -> process(ball); // Compliant, unused variable has been replaced with _ |
| 44 | + case BlueBall blue -> processColor(blue); // Compliant, variable blue is used |
| 45 | + case GreenBall _ -> stopProcessing(); // Compliant |
| 46 | + } |
| 47 | + if (r instanceof ColoredPoint(Point(int x, _), _)) { // Compliant, no unused named variables |
| 48 | + System.out.println("x: " + x); |
| 49 | + } |
| 50 | +} |
| 51 | +---- |
| 52 | + |
| 53 | +== Resources |
| 54 | + |
| 55 | +* https://openjdk.org/jeps/456[JEP 456: Unnamed Variables & Patterns] |
| 56 | + |
0 commit comments