Home » Java » Mutable fields should not be "public static"

Mutable fields should not be "public static"

Posted by: admin December 28, 2021 Leave a comment

Questions:

I getting sonarQube error of below line, any suggestion experts how to resolve this? Thanks in advance

    protected static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
            "account","emailAdress","mobilePhoneNumber","emailStatus"};
Answers:

You can change this array into a private variable.

Then add a static method that returns a copy of this array, or an immutable List backed by this array.

For example:

private static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
        "account","emailAdress","mobilePhoneNumber","emailStatus"};

protected static List<String> getColumnNames() {
    return Collections.unmodifiableList(Arrays.asList(COLUMN_NAMES));
}

Or you can replace the array variable with an unmodifiable List instead of using the method. That would be more efficient (since the List will be created once instead of in every call to the static method):

protected static List<String> COLUMN_NAMES = Collections.unmodifiableList(Arrays.asList("date","customerNumber","customerName",
        "account","emailAdress","mobilePhoneNumber","emailStatus"));

###

You can make COLUMN_NAMES private and simply return clone of it like below:

private static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
        "account","emailAdress","mobilePhoneNumber","emailStatus"};

protected static String[] getCloneArray()
{
  return COLUMN_NAMES.clone();
}

In this way your original array will not be modified.