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

Improve rules relying on String literals to support identifier from a final or effectively final variable.

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 6.15
    • Component/s: Rules
    • Labels:
      None

      Description

      In many rules, we want the string value of an expression. We always support the simple case, when the expression is directly a string literal:

      SSLContext.getInstance("SSL"); // Noncompliant: Change this code to use a stronger protocol.
      

      However, it is not rare to have an identifier referring to a final String instead of the literal:

      private static final String PROTOCOL = "SSL";
      SSLContext.getInstance(PROTOCOL); // No issue?
      

      Currently, we are not supporting this situation in many rules despite the fact that we have all the tools to support this with very little effort.

      More specifically, in addition to supporting string literals, this will add the support for:

      • identifier referring to static final variable in the same file
      • identifier referring to static final variable in another file/dependency
      • text block, once SONARJAVA-3736 is implemented

      Rules that could benefit from this improvement:

      How

      The typical pattern used in these rules is:

      if (expression.is(Tree.Kind.STRING_LITERAL)) {
          String str= trimQuotes(((LiteralTree) expression).value());
          doSomething(str);
      }
      

      Simply changing this code to:

      expression.asConstant(String.class).ifPresent(str -> doSomething(str));
      

      will have the same behavior with the advantages described above.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                quentin.jaquier Quentin Jaquier
                Reporter:
                quentin.jaquier Quentin Jaquier
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Due:
                  Created:
                  Updated:
                  Resolved: