I’m using
- SonarLint for Eclipse 7.3.0.44160
- Eclipse Version: 2022-03 (4.23.0), Build id: 20220310-1457
- No connected mode
and I’m having the same issue as in S131 false positive for enhanced switch merged statements (issue already closed, so I cannot answer):
public enum Position {
FIRST,
SECOND,
THIRD
}
public class TestClass {
public void testMethod(Position pos) {
switch (pos) { // <---- FALSE POSITIVE S131
case FIRST, SECOND -> doSomething();
case THIRD -> doSomethingElse();
}
}
}
but the solution provided there is not sufficient or appropriate for the following reasons:
-
One suggestion is to “just don’t have a duplicate branch” and using
default
instead like this:switch (pos) { case THIRD -> doSomethingElse(); default -> doSomething(); }
This will not work if you have multiple “duplicate” branches, like
switch (pos) { case FIRST, SECOND -> doSomething(); case THIRD, FOURTH -> doSomethingElse(); case FIFTH, SIXTH -> doSomethingEvenDifferent(); }
because you cannot cover these with a simple
default
. -
Another suggestion is to add a default case.
This is also unfavorable because if someone adds an entry to the enum (e.g.FOURTH
in the example), you won’t notice that you forgot to actually cover that case in the switch and it will just be “covered” by the default, even if you actually needed to do something specifically for theFOURTH
case in the switch, but you won’t notice until you actually discover the wrong behavior. No Sonar warning, no compile time error. If you omit thedefault
, you have at least the chance to either get- a justified
S131
warning or - a compiler error (see e.g. Eclipse → Preferences → Java → Compiler → Errors/Warnings → Potential programming problems → Incomplete ‘switch’ cases on enum)
This argument also applies to 1.
- a justified
-
var result = switch (pos) { // NO S131 warning case FIRST, SECOND -> doSomething(); case THIRD -> doSomethingElse(); };
is a partial solution, which only works if the switch returns something, so it doesn’t work for functions returning
void
.
Furthermore, the answer suggests that this is intended behavior, which I doubt, given the rule description.
Anyway, the exception of the rule description of S131 written in the rule itself simply does not apply correctly:
If the
switch
parameter is anEnum
and if all the constants of this enum are used in thecase
statements, then nodefault
clause is expected.
Therefore, the suggested “solution” in the thread above is not a solution. I should not be compelled to add a default
case according to the rule. This still looks like a bug in the rule implementation and the suggested solutions in the thread above do not remedy the problem.