S6880 Use switch instead of if else for pattern matching

Description

  1. JDK: 21

  2. Type: New feature

  3. Link to official doc: JEP 440: Record pattern, JEP 441: Pattern Matching for Switch

  4. Problem to solve:

    • users stick with old instance of and cast, i.e., explicit cast approach, instead of pattern matching.

    • This is true for record types and non record types. Although seen as two different features from JEP perspective, they should both be handled by the same rule, as there is no difference from the user perspective.

  5. Value for user: high

  6. Estimated usage %: 100% of those using Java 21 and records

  7. NOTE:

    1. This rule is about simple pattern matching only. For pattern matching involving decomposition declarations, see

    2. Also, this rule is about switch statements only. For other control structures (if, while, for, conditional expressions and boolean shortcut expressions), see .

    3. However, this rule is about both, record and non-record types

  8. Rule definition:

== Why is this an issue?

In versions of Java before 21, matching a variable against multiple patterns required a chain of if/else statements. However, since Java 21, the enhanced switch expression is a preferable alternative in most scenarios. Using a switch expression provides advantages such as clearer code, assurance of handling all cases, and improved performance.

If a variable is matched against more than one pattern and can be replaced by a switch expression, we raise an issue.

=== Noncompliant code example

=== Compliant solution

=== Message

Replace the chain of if/else with a switch expression.

== Resources

=== Documentation

Activity

Done
Pinned fields
Click on the next to a field label to start pinning.

Details

Assignee

Reporter

Labels

Components

Fix versions

Priority

Sentry

Created January 31, 2024 at 1:10 PM
Updated October 16, 2024 at 2:06 PM
Resolved March 22, 2024 at 9:17 AM