我有一个实用类,其中包含一些值的静态常量映射。我需要在另一个类中访问此映射。我应该将映射声明为公共的,还是应该在实用类内编写一个getter,从而使映射成为私有的?
两种方法都可以,但最佳实践是什么呢?
public MyUtilityClass {
public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
"title", 256,
"text", 512);
}
public MyAnotherClass {
public void someMethod() {
//accessing the map directly
MAX_LENGTHS.get("title")
}
}
或者
public MyUtilityClass {
private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
"title", 256,
"text", 512);
public static final getMaxLengthMap() {return MAX_LENGTHS;}
}
public MyAnotherClass {
public void someMethod() {
//accessing the map directly
getMaxLengthMap().get("title")
}
}
实际上,这些键是枚举值。 类似于:
private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
MyEnumClass.TITLE, 256,
MyEnumClass.TEXT, 512);
MyUtilityClass
上的“getter”应该返回键的值,而不是类的用户必须知道键是什么或如何存储。 - MadProgrammer