javapropertiesconfigurationhard-coding

Java: Using key names from properties file without using hardcoded strings as keys


Problem statement

I have a properties file that's accessed throughout my java project.

Example contents of my .properties file:

appName=MyApp
appType=TypeA

Let's say I access the single property, appName, all throughout my java project

props.getProperty("appName");

I don't want to iterate through the properties file to get the property value; I'm just simply getting a single property value from the properties file. But I don't like the fact that I have to access the property by using a hardcoded string because it can lead to maintenance issues (i.e. changing all instances of the hardcoded string).

My current approach

In my current approach, I have a utility class that creates static final variables representing the key names in the properties file, and then I use that variable to access the property value:

public static final String APP_NAME = "appName";
...
props.getProperty(APP_NAME);

But this seems like overkill because it's being redundant, and still a potential maintenance concern. The key already exists in the properties file, and I'm declaring them again in my utility class.

Is there a more "maintenance-free" way of accessing the key name in my code when using the get methods to access property values?


Solution

  • No, you're doing it right. And it's actually fairly maintenance-free.

    Using Java Enums would be slightly preferable - i.e.

    public class PropertiesWrapper {
       private final Properties props;
       ...
       public String get(MyEnum key) {  return props.get(key.toString());
    }
    

    The reason is that even if you make that String a constant, you can never change it without recompiling all code which uses the constant - because the compiler will replace the constant with "appName" at compile-time.

    If you use enums and remove an enum constant, code will still need recompiling, but it won't appear to be fine when it's actually now asking for the wrong thing. Also, by using toString() instead of name() to get the property name, you are free to override toString() in your enum to return something different than the constant name.

    The down-side of using enums is that the system can't look up anything which was not known at compile-time without some alternate way to access the Properties.