I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?
Both ways work, but what are the best practices?
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")
  }
}
Or
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")
  }
}
Well, actually the keys are enum values. Something like :
private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);
                The getter does not add anything - I would just keep it public.
What may make sense is to have a method that returns the value directly:
public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);
  public static final getMaxLength(String item) {return MAX_LENGTHS.get(item);}
}
public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLength("title");
  }
}
This also allows you to easily modify the underlying implementation later on. For example you could return a default value for items not in the map etc.
You are using ImmutableMap from guava project; thus a true immutable Map. 
Making it public would not hurt anyone - as no one can really alter that Map in any way. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With