Make sure to read this post before raising a thread here:
Then tell us:
- What language is this for? Java
- Which rule? java:S1301
- Why do you believe it’s a false-positive/false-negative? False positive
- Are you using
- SonarQube Cloud?
- SonarQube Server / Community Build - which version? 9.9.1 (build 69595)
- SonarQube for IDE - which IDE/version?
- in connected mode with SonarQube Server / Community Build or SonarQube Cloud?
- How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
Before Java 14, you had to write code like this, and it wouldn’t get flagged:
private void setFoo(String bar) {
switch (bar) {
case: "potato":
case: "tomato":
case: "oregano":
baz();
break;
default:
noBaz();
}
}
In Java 14 and newer, you can write combined case statements:
private void setFoo(String bar) {
switch (bar) {
case: "potato","tomato","oregano":
baz();
break;
default:
noBaz();
}
}
However, the java:S1301 rule has not been updated to account for combined case statements and will complain about the above example, suggesting an if
is an appropriate substitute. With an if, the code will be much less readable:
private void setFoo(String bar) {
if ("potato".equals(bar) || "tomato".equals(bar) || "oregano".equals(bar)) {
baz();
} else {
noBaz();
}
}
Or will require creating a list, necessitating memory allocation:
private void setFoo(String bar) {
if (List.of("potato", "tomato", "oregano").contains(bar)) {
baz();
} else {
noBaz();
}
}
It would be nice if each of the coma delimited parts of the case statement counted against the “3 minimum conditions” threshold and this switch statement wasn’t flagged.