Uploaded image for project: 'SonarJava'
  1. SonarJava
  2. SONARJAVA-3740

Extend rule S1481 to report on unused variables in pattern matching on instanceof

    Details

    • Type: Improvement
    • Status: Open
    • Priority: Major
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: None
    • Component/s: Rules
    • Labels:
      None

      Description

      In Java 16 there is a new feature called pattern matching on instanceof (see JEP 394). It simplifies a lot the way developers do type checks and casts. There are situations when after the variable is tested and casted, the resulting value is not used. In such cases pattern matching is odd and a simple instanceof check is enough. And the analyser should report that variable is not used.

      Noncompliant Code Example

      int f(Object o) {
        if (o instanceof String string) {  // Noncompliant
          return 42;
        }
        return 0;
      }
      

      Compliant Solution

      int f(Object o) {
        if (o instanceof String) {  // Compliant
          return 42;
        }
        return 0;
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                margarita.nedzelska Margarita Nedzelska
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: