Search code examples
javaarrayssonarqube

SonarQube issue with public static variables | JAVA


I'm having an issue with SonarQube while using public static variables, the problem is that SonarQube want that to be public static final, this variable is being filled in other parts of the code, it is "dynamically" (filled with environment variable) then is used in all other classes.

This is the arrayList variable

public static List<String> listPersons = new ArrayList<>();

Errors by Sonar:

1- Make this "public static listPersons" field final
2- Make listPersons a static final constant or non-public and provide accessors if needed
3- Make this member "protected"

What's the best approach to fix this problem?


Solution

  • Technically, you can have the (reference of) the variable final and still have its contents dynamically filled at some later point:

    public static final List<String> listPersons = new ArrayList<>();
    
    //...
    
    public void initialize() {
        List<String> contents = populateContentsFromEnvironmentVariable();
        listPersons.addAll(contents);
    }
    

    However, using a "mutable-content" constant such as this one introduces possible problems. For example, you need to make sure that client code doesn't read the list before it has been populated. You might want to reconsider your design so that environment-specific properties are only initialized once and preferably encapsulated so that they are accessed through accessor methods instead of static constants; this would also allow lazy, on-demand initialization, caching etc.