Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java best practices static final map values [closed]

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);
like image 758
josefk Avatar asked May 28 '19 09:05

josefk


2 Answers

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.

like image 158
assylias Avatar answered Sep 29 '22 02:09

assylias


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.

like image 22
Eugene Avatar answered Sep 29 '22 00:09

Eugene