Maana
Maana

Reputation: 700

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"};

Upvotes: 6

Views: 13548

Answers (2)

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

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.

Upvotes: 4

Eran
Eran

Reputation: 393896

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"));

Upvotes: 12

Related Questions