S1301 false positive when switching over enums with 2 values

If your question is about SonarQube for IDE in the IntelliJ Platform, VS Code, Visual Studio, or Eclipse, please post it in that sub-category.

Otherwise, please provide:

  • Operating system: Windows
  • IDE name and flavor/env: IntelliJ Ultimate

And a thorough description of the problem / question:

When switching over enums with 2 or less values S1301 will fire and tell you to use if statements. This is a false positive because you want switch exhaustion over enums.

enum Something {
   ONE, TWO
}

var s = ONE;
switch (s) { <-- S1301 here
   case ONE -> ...;
   case TWO -> ...;
}

Hi George,

Thank you for the report! I created a ticket, SONARJAVA-5730, to track this problem.

The rules predates switch expressions (the ones with ->) and they may indeed be more readable than an if statement, so we will discuss how to relax the rule.

Hi,

I don’t know the state of this ticket (but the Jira does not seem to be worked on).

I just want to add that this is not a readability issue like Tomasz suggests. The sonarqube suggestion is way worse to the original code:

If now the Something enum is a appended with THREE, the original code will lead to a compile time error, while the sonarqube suggested solution will happily compile and will be kept unnoticed.

Both codes do entirely different things at compile time. I think that readability (of which I disagree with one being better/worse than the other) should not be preferred over the overall compile time security.

Thank you for pointing this out, Colin! Yes, this is a convincing argument for changing this rule. I updated the ticket and marked it as a false positive.