简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM