java:S131 reports false positive when combining labels

  • What language is this for?
    Java
  • Which rule?
    java:S131
  • Why do you believe it’s a false-positive/false-negative?
  • Are you using
    • SonarQube Cloud?
    • SonarQube Server / Community Build - which version?
    • SonarQube for IDE - which IDE/version?
      • in connected mode with SonarQube Server / Community Build or SonarQube Cloud?
        Developer Edition v10.5.1 (90531)
  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)

An exhaustive switch statement over an enum might look like this:

class Scratch {

    enum SomeEnum {
        OPEN,
        CLOSED,
        ON_HOLD
    }

    public static void main(String[] args) {
        SomeEnum status  = SomeEnum.CLOSED;
        switch(status) {
            case CLOSED -> System.out.println("Not Open");
            case ON_HOLD -> System.out.println("Not Open");
            case OPEN -> System.out.println("Open");
        }
    }

}

In this example, the code called for both the CLOSED and ON_HOLD labels is the same, so naturally one wants to condense the switch statement:

        switch(status) {
            case CLOSED, ON_HOLD -> System.out.println("Not Open");
            case OPEN -> System.out.println("Open");
        }

In this example, rule java:S131 falsely reports that this switch statement should have a default case. SonarLint plugin for IntelliJ v10.12.0.79769 Does not report on this example.

Hey there

Has this project been analyzed recently? I believe SONARJAVA-4908 should have fixed this, and it was included in SonarQube v10.5.1.

In any case, SonarLint for IntelliJ is using newer versions of the analyzers, so your problem may be fixed by simply upgrading SonarQube to v10.7 (v10.5 is EOL anyhow)

The project has indeed been analyzed recently (less than an hour ago).

If it has been fixed in newer versions of SQ I’ll try and apply some gentle pressure on the team that is responsible for updating our SQ instance.

SONARJAVA-4908 refers to type patterns, while my example uses an Enum. I cannot tell for certain if that case is also addressed in the referenced issue.

I was also looking at another issue with similar switch statements about rule Java:S1301.

Reports some issues with switch statements using type patterns, among which the aforementioned SONARJAVA-4908. Similarly to this issue SONARJAVA-4904 applies to Java:S1301 for type patterns. Perhaps in general Enum patterns were overlooked? Many of the same logic about exhaustiveness applies.