Skip to content

[java] SwitchStmtsShouldHaveDefault false positive with pattern matching #4813

@emouty

Description

@emouty

Affects PMD Version: 7.0.0-rc4

Rule:

Please provide the rule name and a link to the rule documentation:

Description:

Code Sample demonstrating the issue:

    public sealed interface AcceptableResult permits Success, Warning {
        public String message();
    }

    public final class Success implements AcceptableResult {

        @Override
        public String message() {
            return "Success!";
        }
    }

    public abstract class Failure {

        abstract public String message();
    }

    public non-sealed class Warning extends Failure implements AcceptableResult {

        @Override
        public String message() {
            return "Oopsie";
        }
    }

    public class ProviderWarning extends Warning {

        @Override
        public String message() {
            return "Ohoh";
        }
    }

    public void test(AcceptableResult result) {
        switch (result) {
            case Warning failure -> System.out.println("WARNING " + failure.message());
            case Success success -> System.out.println(success.message());
        }
    }

Expected outcome:

PMD reports violations on the switch SwitchStmtsShouldHaveDefault and TooFewBranchesForASwitchStatement. For SwitchStmtsShouldHaveDefault it's a false positive since we have covered all of the cases here. As for TooFewBranchesForASwitchStatement I think it's also a false positive in this case, since using a pattern matching switch is the cleanest way to do this kind of stuff even if there are only 2 branches.

Running PMD through: * Maven*

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positivePMD flags a piece of code that is not problematic

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions