S2386 Mutable fields should not be "public static"

Reporting a False Positive.

I have have a java public static final Set composed of String values that I use validate input. The set is constructed from Collectors.toUnmodifiableSet(). I need to be able to access the set in other classes. It is possible to create a method to call contains on the set, but that kind of boiler plate should be avoided.

  public static final Set<String> azureUpdate =
      Arrays.asList(
              PASSWORD,
              SECRET_QUESTIONS_AND_RESPONSES,
              IS_ACCOUNT_ENABLED,
              DISPLAY_NAME,
              FIRST_NAME,
              LAST_NAME)
          .stream()
          .collect(Collectors.toUnmodifiableSet());

The more I look at this the less I like the idea of writing one off static methods that perform operations that access the unmodifiable set for instance I want to see if a list contains one of the strings in set. It is natural to do the following:

if (attributes.stream().anyMatch(LiamUserHelper.azureUpdate::contains)) {
      azureB2cManager.updateUser(currentUser, attributes);
    }

Calling a static method in another class to do this can be done, but it is less concise and obfuscates what is going on. Similarly removing matches of this set from a superset suffers the same weaknesses. Someone maintaining this code has to jump back and forth between files to see the implementation. Providing a bunch of static methods to avoid the side effect of someone attempting to change the contents of an unmodifiable set is just silly.

Hi,

You’re reporting this in SonarLint, so could you share your flavor & version?

 
Ann

intelij plugin 6.7.0.5.459, but the same errors are reported from our pipeline.

SonarQube™ technology is powered by SonarSource SA

  • Community Edition
  • Version 8.9.6 (build 50800)

Hello @rtrask

Thanks for reporting this issue, I agree that the case you described seems legitimate. In fact, the rule has an exception for such use-case but is not correctly supporting when the collection is created from a stream. Ticket created to improve the situation: SONARJAVA-4252.

Best,
Quentin

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.