Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutable fields should not be "public static"

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"};
like image 820
Maana Avatar asked Dec 13 '18 15:12

Maana


2 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"));
like image 156
Eran Avatar answered Nov 11 '22 15:11

Eran


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.

like image 44
Shubhendu Pramanik Avatar answered Nov 11 '22 17:11

Shubhendu Pramanik