Skip to content

Commit

Permalink
SONARJAVA-4904 FP on S1301 when using switch statement with type/reco…
Browse files Browse the repository at this point in the history
…rd/guarded patterns
  • Loading branch information
leonardo-pilastri-sonarsource authored and Wohops committed Mar 18, 2024
1 parent 8617962 commit b0b57a4
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,22 @@ public void visitNode(Tree tree) {
SwitchStatementTree switchStatementTree = (SwitchStatementTree) tree;
int count = 0;
for (CaseGroupTree caseGroup : switchStatementTree.cases()) {
// whenever there is a type, record or guarded pattern, it would decrease readability to replace the switch by if
// so we don't raise an issue
if (hasLabelWithAllowedPattern(caseGroup)) {
return;
}
count += caseGroup.labels().size();
}
if (count < 3) {
reportIssue(switchStatementTree.switchKeyword(), "Replace this \"switch\" statement by \"if\" statements to increase readability.");
}
}

private static boolean hasLabelWithAllowedPattern(CaseGroupTree caseGroupTree) {
return caseGroupTree.labels().stream()
.flatMap(label -> label.expressions().stream())
.anyMatch(expression -> expression.is(Tree.Kind.TYPE_PATTERN, Tree.Kind.RECORD_PATTERN, Tree.Kind.GUARDED_PATTERN));
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,39 @@
class A {

static void recordSwitch1(MyRecord object) {
switch (object) { // Compliant
case String x when x.length() > 42 -> { }
case Integer i -> { }
}
}

static void recordSwitch1(Object object) {
switch (object) { // Compliant
case MyRecord(int x, int y) -> { }
case String s -> { }
}
}

public interface SealedClass {
sealed interface Shape permits Box, Circle {}
record Box() implements Shape { }
record Circle() implements Shape {}

void foo(Shape shape) {
switch (shape) { // Compliant because of type pattern matching
case Box ignored -> { }
case Circle ignored -> System.out.println();
}
}

void goo(Shape shape) {
switch (shape) { // Compliant because of type pattern matching
default -> System.out.println();
case Box ignored -> { }
}
}
}

public void f() {
switch (variable) { // Noncompliant [[sc=5;ec=11]] {{Replace this "switch" statement by "if" statements to increase readability.}}
case 0:
Expand Down

0 comments on commit b0b57a4

Please sign in to comment.