Skip to content

Commit 2bca513

Browse files
Fix on switch on enum
1 parent 560700b commit 2bca513

2 files changed

Lines changed: 43 additions & 1 deletion

File tree

java-checks-test-sources/default/src/test/java/checks/tests/SwitchAtLeastThreeCasesCheckSample.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,42 @@ public void f(int variable) {
7979
doSomethingElse();
8080
}
8181
}
82+
83+
public enum SmallEnum {
84+
ONE,
85+
TWO
86+
}
87+
88+
public void switchOverSmallEnum1(SmallEnum smallEnum) {
89+
switch (smallEnum) {
90+
case ONE -> {
91+
System.out.println("1");
92+
}
93+
case TWO -> {
94+
System.out.println("2");
95+
}
96+
};
97+
}
98+
99+
public int switchOverSmallEnum2(SmallEnum smallEnum) {
100+
int ret = -1;
101+
switch (smallEnum) {
102+
case ONE:
103+
ret = 1;
104+
break;
105+
case TWO:
106+
ret = 2;
107+
break;
108+
};
109+
return ret;
110+
}
111+
112+
public int decoy(int x) {
113+
switch(x) { // Noncompliant {{Replace this "switch" statement by "if" statements to increase readability.}}
114+
case 0:
115+
return 1;
116+
default:
117+
throw new IllegalStateException("Unexpected value: " + x);
118+
}
119+
}
82120
}

java-checks/src/main/java/org/sonar/java/checks/SwitchAtLeastThreeCasesCheck.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import org.sonar.check.Rule;
2020
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
21+
import org.sonar.plugins.java.api.semantic.Symbol;
2122
import org.sonar.plugins.java.api.tree.CaseGroupTree;
2223
import org.sonar.plugins.java.api.tree.CaseLabelTree;
2324
import org.sonar.plugins.java.api.tree.SwitchStatementTree;
@@ -46,7 +47,10 @@ public void visitNode(Tree tree) {
4647
count += totalLabelCount(caseGroup);
4748
}
4849
if (count < 3) {
49-
reportIssue(switchStatementTree.switchKeyword(), "Replace this \"switch\" statement by \"if\" statements to increase readability.");
50+
Symbol.TypeSymbol typeSymbol = switchStatementTree.expression().symbolType().symbol();
51+
if (!typeSymbol.isUnknown() && !typeSymbol.isEnum()) {
52+
reportIssue(switchStatementTree.switchKeyword(), "Replace this \"switch\" statement by \"if\" statements to increase readability.");
53+
}
5054
}
5155
}
5256

0 commit comments

Comments
 (0)