Skip to content

SONARJAVA-6867 Replace if/else chains with switch expressions in pattern matching code - #6054

Open
sonarqube-agent[bot] wants to merge 1 commit into
masterfrom
remediate-master-20260828-050309-cc0216ba
Open

SONARJAVA-6867 Replace if/else chains with switch expressions in pattern matching code#6054
sonarqube-agent[bot] wants to merge 1 commit into
masterfrom
remediate-master-20260828-050309-cc0216ba

Conversation

@sonarqube-agent

Copy link
Copy Markdown

This PR was automatically created by the Remediation Agent's Scheduled backlog remediation feature.

Why these issues? All five issues are MAJOR severity violations of rule java:S6880, which recommends replacing if/else chains with switch expressions. This cohesive set of changes across multiple files in the Java checker plugin represents a high-value, low-risk modernization that improves code readability while maintaining identical functionality.

This PR converts five if/else chains that use instanceof checks into modern Java switch expressions with pattern matching. This refactoring improves code clarity, maintainability, and aligns with Java 21+ best practices for type checking and pattern matching.

View Project in SonarCloud


Fixed Issues

java:S6880 - Replace the chain of if/else with a switch expression. • MAJORView issue

Location: java:java-checks/src/main/java/org/sonar/java/checks/TryWithResourcesCheck.java:100

Why is this an issue?

Comparing a variable to multiple cases is a frequent operation. This can be done using a sequence of if-else statements. However, for many cases like enums or simple value comparisons, a switch statement is the better alternative. With Java 21, the switch statement has been significantly improved to support pattern matching and record pattern.

What changed

This hunk replaces the beginning of an if/else chain that uses instanceof checks (starting with if (tree instanceof NewClassTree newClass) and else if (tree instanceof MethodInvocationTree mit)) with a switch expression using pattern matching (return switch (tree) { case NewClassTree newClass -> ...; case MethodInvocationTree mit -> ...;). This directly addresses the code smell about replacing if/else chains with switch expressions at line 100 of TryWithResourcesCheck.java.

--- a/java-checks/src/main/java/org/sonar/java/checks/TryWithResourcesCheck.java
+++ b/java-checks/src/main/java/org/sonar/java/checks/TryWithResourcesCheck.java
@@ -100,4 +100,3 @@ public class TryWithResourcesCheck extends IssuableSubscriptionVisitor implement
-    if (tree instanceof NewClassTree newClass) {
-      return newClass.symbolType().isSubtypeOf("java.lang.AutoCloseable");
-    } else if (tree instanceof MethodInvocationTree mit) {
-      return AUTOCLOSEABLE_FACTORY_MATCHER.matches(mit) ||
+    return switch (tree) {
+      case NewClassTree newClass -> newClass.symbolType().isSubtypeOf("java.lang.AutoCloseable");
+      case MethodInvocationTree mit -> AUTOCLOSEABLE_FACTORY_MATCHER.matches(mit) ||
java:S6880 - Replace the chain of if/else with a switch expression. • MAJORView issue

Location: java:java-checks/src/main/java/org/sonar/java/checks/helpers/StringUtils.java:63

Why is this an issue?

Comparing a variable to multiple cases is a frequent operation. This can be done using a sequence of if-else statements. However, for many cases like enums or simple value comparisons, a switch statement is the better alternative. With Java 21, the switch statement has been significantly improved to support pattern matching and record pattern.

What changed

This hunk replaces an if-else chain using instanceof checks (for String, String[], Collection<?>) with a switch expression using pattern matching. This directly addresses the code smell about replacing if/else chains with switch expressions, as the original code at line 63 of StringUtils.java was flagged for using an if-else chain that should be a switch.

--- a/java-checks/src/main/java/org/sonar/java/checks/helpers/StringUtils.java
+++ b/java-checks/src/main/java/org/sonar/java/checks/helpers/StringUtils.java
@@ -63,8 +63,5 @@ public class StringUtils {
-      if (arg instanceof String s) {
-        result.add(s);
-      } else if (arg instanceof String[] arr) {
-        Collections.addAll(result, arr);
-      } else if (arg instanceof Collection<?> col) {
-        result.addAll((Collection<String>) col);
-      } else {
-        throw new IllegalArgumentException("Unsupported argument type: " + arg.getClass());
+      switch (arg) {
+        case String s -> result.add(s);
+        case String[] arr -> Collections.addAll(result, arr);
+        case Collection<?> col -> result.addAll((Collection<String>) col);
+        default -> throw new IllegalArgumentException("Unsupported argument type: " + arg.getClass());
java:S6880 - Replace the chain of if/else with a switch expression. • MAJORView issue

Location: java:java-checks/src/main/java/org/sonar/java/checks/DateTimeConversionsCheck.java:102

Why is this an issue?

Comparing a variable to multiple cases is a frequent operation. This can be done using a sequence of if-else statements. However, for many cases like enums or simple value comparisons, a switch statement is the better alternative. With Java 21, the switch statement has been significantly improved to support pattern matching and record pattern.

What changed

This hunk replaces an if-else chain using instanceof pattern matching with a switch expression at line 102 of DateTimeConversionsCheck.java. The original code used if (result instanceof ParenthesizedTree ...) ... else if (result instanceof TypeCastTree ...) ... else ..., which the static analysis rule flagged as a code smell that should be converted to a switch statement. The new code uses a switch (result) with pattern matching cases (case ParenthesizedTree, case TypeCastTree, default), which is cleaner and follows the recommended Java 21+ switch pattern matching style. This single hunk addresses the issue about replacing if/else chains with switch expressions, providing clearer code structure and potentially better performance.

--- a/java-checks/src/main/java/org/sonar/java/checks/DateTimeConversionsCheck.java
+++ b/java-checks/src/main/java/org/sonar/java/checks/DateTimeConversionsCheck.java
@@ -102,6 +102,4 @@ public class DateTimeConversionsCheck extends AbstractMethodDetection implements
-      if (result instanceof ParenthesizedTree parenthesizedTree) {
-        result = parenthesizedTree.expression();
-      } else if (result instanceof TypeCastTree typeCastTree) {
-        result = typeCastTree.expression();
-      } else {
-        return result;
+      switch (result) {
+        case ParenthesizedTree parenthesizedTree -> result = parenthesizedTree.expression();
+        case TypeCastTree typeCastTree -> result = typeCastTree.expression();
+        default -> { return result; }
java:S6880 - Replace the chain of if/else with a switch expression. • MAJORView issue

Location: java:java-checks/src/main/java/org/sonar/java/checks/PatternMatchUsingIfCheck.java:220

Why is this an issue?

Comparing a variable to multiple cases is a frequent operation. This can be done using a sequence of if-else statements. However, for many cases like enums or simple value comparisons, a switch statement is the better alternative. With Java 21, the switch statement has been significantly improved to support pattern matching and record pattern.

What changed

This hunk replaces the beginning of an if-else chain that checks caze instanceof PatternMatchCase with a switch expression using pattern matching (switch (caze) { case PatternMatchCase patternMatchCase -> { ... }). This directly addresses the code smell about replacing if/else chains with switch expressions at line 220 of PatternMatchUsingIfCheck.java, as the original code used if (caze instanceof PatternMatchCase) followed by else if and else branches. The issue is that comparing a variable to multiple cases via if-else chains should be replaced with a switch statement for clearer code and better performance.

--- a/java-checks/src/main/java/org/sonar/java/checks/PatternMatchUsingIfCheck.java
+++ b/java-checks/src/main/java/org/sonar/java/checks/PatternMatchUsingIfCheck.java
@@ -220,6 +220,8 @@ public class PatternMatchUsingIfCheck extends IssuableSubscriptionVisitor implem
-    if (caze instanceof PatternMatchCase patternMatchCase) {
-      sb.append("case ").append(QuickFixHelper.contentForTree(patternMatchCase.pattern, context));
-      if (!patternMatchCase.guards().isEmpty()) {
-        List<ExpressionTree> guards = patternMatchCase.guards();
-        sb.append(" when ");
-        join(guards, " && ", sb);
+    switch (caze) {
+      case PatternMatchCase patternMatchCase -> {
+        sb.append("case ").append(QuickFixHelper.contentForTree(patternMatchCase.pattern, context));
+        if (!patternMatchCase.guards().isEmpty()) {
+          List<ExpressionTree> guards = patternMatchCase.guards();
+          sb.append(" when ");
+          join(guards, " && ", sb);
+        }
java:S6880 - Replace the chain of if/else with a switch expression. • MAJORView issue

Location: java:java-frontend/src/main/java/org/sonar/java/model/JSymbolMetadata.java:411

Why is this an issue?

Comparing a variable to multiple cases is a frequent operation. This can be done using a sequence of if-else statements. However, for many cases like enums or simple value comparisons, a switch statement is the better alternative. With Java 21, the switch statement has been significantly improved to support pattern matching and record pattern.

What changed

This hunk replaces a chain of if/else statements in JSymbolMetadata.java that check the type of symbol using method calls (isVariableSymbol(), isMethodSymbol(), isTypeSymbol(), isPackageSymbol()) with a switch expression using pattern matching. The original if-else chain compared a variable against multiple cases, which the static analysis flagged as a code smell recommending replacement with a switch expression for clearer code and better structure. The new switch expression matches symbol against Symbol.VariableSymbol, Symbol.MethodSymbol, and Symbol.TypeSymbol patterns, with a default case handling the package symbol and unknown cases. This directly addresses the rule that an if/else chain should be replaced by a switch expression, as reported at line 411 of JSymbolMetadata.java.

--- a/java-frontend/src/main/java/org/sonar/java/model/JSymbolMetadata.java
+++ b/java-frontend/src/main/java/org/sonar/java/model/JSymbolMetadata.java
@@ -266,10 +266,6 @@ final class JSymbolMetadata implements SymbolMetadata {
-    if (symbol.isVariableSymbol()) {
-      return NullabilityLevel.VARIABLE;
-    } else if (symbol.isMethodSymbol()) {
-      return NullabilityLevel.METHOD;
-    } else if (symbol.isTypeSymbol()) {
-      return NullabilityLevel.CLASS;
-    } else if (symbol.isPackageSymbol()) {
-      return NullabilityLevel.PACKAGE;
-    }
-    return NullabilityLevel.UNKNOWN;
+    return switch (symbol) {
+      case Symbol.VariableSymbol v -> NullabilityLevel.VARIABLE;
+      case Symbol.MethodSymbol m -> NullabilityLevel.METHOD;
+      case Symbol.TypeSymbol t -> NullabilityLevel.CLASS;
+      default -> symbol.isPackageSymbol() ? NullabilityLevel.PACKAGE : NullabilityLevel.UNKNOWN;
+    };

Have a suggestion or found an issue? Share your feedback here.


SonarQube Remediation Agent uses AI. Check for mistakes.

Fixed issues:
- AaBB4bdV2vS79_8iEWy1 for java:S6880 rule
- AaBB4b6D2vS79_8iEWy6 for java:S6880 rule
- AaBB4ayF2vS79_8iEWy0 for java:S6880 rule
- AaBB4bvV2vS79_8iEWy4 for java:S6880 rule
- AaBB4cC32vS79_8iEWy7 for java:S6880 rule

Generated by SonarQube Agent (task: 97a02fde-db70-41f7-b2b8-6e16fcbf96b3)
@hashicorp-vault-sonar-prod hashicorp-vault-sonar-prod Bot changed the title Replace if/else chains with switch expressions in pattern matching code SONARJAVA-6867 Replace if/else chains with switch expressions in pattern matching code Aug 28, 2026
@hashicorp-vault-sonar-prod

hashicorp-vault-sonar-prod Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

SONARJAVA-6867

@sonarqube-next

Copy link
Copy Markdown
Contributor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant