A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/pmd/pmd/issues/5249 below:

[java] TooFewBranchesForASwitchStatement false positive for Pattern Matching · Issue #5249 · pmd/pmd · GitHub

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


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4