Affects PMD Version: 7.6.0
Rule: TooFewBranchesForASwitchStatement
Description:
When using Pattern Matching for Switch, this rule reports a violation when there are too few branches.
However, using a switch is preferable, as the compiler will do exhaustiveness check and generate a compiler error, if the switch doesn't cover all cases. Would the switch be rewritten with if-else, like the rule suggests, then there will never be a compiler error if a new case appears (e.g. a new subclass of a sealed class is added).
Code Sample demonstrating the issue:
sealed interface S permits A {}
final class A implements S {}
public class Sample {
public void simpleSwitchStatment(S s) {
switch(s) { // violation here
case A a -> System.out.println("a");
}
}
public void simpleSwitchExpression(S s) {
String result = switch(s) { // violation here
case A a -> "a";
};
}
}
Expected outcome:
PMD reports a violation at line ..., but that's wrong. That's a false positive.
Even though, this switch has only once case, this is preferable: if in the future final class B implements S {} is added, the compiler will generate an error, as the switch becomes suddenly non-exhaustive.
Running PMD through: [CLI | Ant | Maven | Gradle | Designer | Other]
Originally reported in #4813 by @emouty
Affects PMD Version: 7.6.0
Rule: TooFewBranchesForASwitchStatement
Description:
When using Pattern Matching for Switch, this rule reports a violation when there are too few branches.
However, using a switch is preferable, as the compiler will do exhaustiveness check and generate a compiler error, if the switch doesn't cover all cases. Would the switch be rewritten with if-else, like the rule suggests, then there will never be a compiler error if a new case appears (e.g. a new subclass of a sealed class is added).
Code Sample demonstrating the issue:
Expected outcome:
PMD reports a violation at line ..., but that's wrong. That's a false positive.
Even though, this switch has only once case, this is preferable: if in the future
final class B implements S {}is added, the compiler will generate an error, as the switch becomes suddenly non-exhaustive.Running PMD through: [CLI | Ant | Maven | Gradle | Designer | Other]
Originally reported in #4813 by @emouty