不应"public static"可变字段



我得到了下面一行的sonarQube错误,有什么建议专家如何解决吗?提前感谢

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

您可以将此数组更改为private变量。

然后添加一个返回此数组副本的static方法,或此数组支持的不可变List

例如:

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

或者,您可以将数组变量替换为不可修改的List,而不是使用方法。这将更有效(因为List将创建一次,而不是在每次调用static方法时创建(:

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

您可以将COLUMN_NAMES设为私有,只需返回其克隆,如下所示:

private static final String [] COLUMN_NAMES = new String[]{"date","customerNumber","customerName",
"account","emailAdress","mobilePhoneNumber","emailStatus"};
protected static String[] getCloneArray()
{
return COLUMN_NAMES.clone();
}

通过这种方式,您的原始数组将不会被修改。

最新更新