<分区>
我有一个实用程序类,其中包含一个带有一些值的静态最终映射。我需要在另一个类(class)访问这张 map 。我应该只将 map 声明为公共(public)的,还是应该在实用程序类中编写一个 getter,从而让 map 成为私有(private)的?
两种方法都有效,但最佳做法是什么?
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);