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

FP in S2384, S2386: support any unmodifiable and immutable methods

    Details

    • Type: False-Positive
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 6.14
    • Component/s: Rules
    • Labels:

      Description

      Java does not support natively some types to distinguish mutable and immutable objects. There are some methods like Collections.unmodifiableList(list) to convert a list to an immutable list, but the "List<T>" result is not typed immutable.
      So rules like S2384 and S2386 can assume that an object is immutable when there's a call to "Collections.unmodifiableList", but the rule implementation is not able to know when the effective runtime type of an object coming from any method is for example "java.util.Collections.UnmodifiableList".

      public final class TestS2386 {
      
      	public static final List<String> LIST1 = Collections.unmodifiableList(create("a")); // S2386 Compliant
      
      	public static final List<String> LIST2 = createUnmodifiable("a"); // S2386 false-positive
      
      	private TestS2386() {
      	}
      
      	private static List<String> create(String value) {
      		return new ArrayList<>(Arrays.asList(value));
      	}
      
      	private static List<String> createUnmodifiable(String value) {
      		return Collections.unmodifiableList(create(value));
      	}
      
      }
      

      Being able to dig into any method calls and track which object is immutable is not yet supported by the java analyzer. But to reduce false-positives, the rule S2384 and S2386 could at least consider any method calls containing "unmodifiable" or "immutable" as returning immutable objects.

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                alban.auzeill Alban Auzeill
                Reporter:
                alban.auzeill Alban Auzeill
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Due:
                  Created:
                  Updated:
                  Resolved: