Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
Javier Salas Avatar asked Oct 21 '25 05:10

Javier Salas


2 Answers

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.

like image 168
Mick Mnemonic Avatar answered Oct 23 '25 22:10

Mick Mnemonic


The best approach is not to create public static but not final fields. Because it can lead to problems with sharing this data between threads.

In your case, you can create a static final and immutable list.

like image 23
dehasi Avatar answered Oct 23 '25 22:10

dehasi