Search code examples
javaencapsulationsoftware-design

Encapsulating java.util.Properties access through accessor methods considered bad practice?


I am using java.util.Properties for a project I am working on. I have a class that manages a .properties file with a Properties instance, called PropertiesManager. This class manages the loading and saving of the .properties file from disc.

Now because I wanted to make sure that one could only access valid properties and that default values were used whenever a property is not in the file, I added getters and setters for each property of the file.

The Problem is that makes the class PropertiesManager very big. The getters and setters alone (with comments/blank lines) are 300 lines of code. So even if I transfer the loading/saving in another class (inheritance etc.) it is still way to big.

This is not the actual code but it gives you the idea:

import java.util.Properties;

public class PropertiesManager {
    private Properties properties;

    public PropertiesManager() {
        // constructor
    }

    private void save() {
        // save in .properties file
    }

    private void load() {
        // load from .properties file
    }

    public String getPropertyName1() {
        return properties.getProperty("PropertyName1", "Property1DefaultValue");
    }

    // 28 more getters here

    public String getPropertyName30() {
        return properties.getProperty("PropertyName30", "Property30DefaultValue");
    }

    public void setPropertyName1(String value) {
        properties.setProperty("PropertyName1", value);
    }

    // 28 more more setters here

    public void setPropertyName30(String value) {
        properties.setProperty("PropertyName30", value);
    }
}

Is it considered bad practice to encapsulate your access to the Properties instance like this? Should I just use the Properties instance directly instead of using accessor methods? Is there another solution?


Solution

  • I would just change it to have a single getter/setter using an enum:

    public class PropertiesManager {
        ...
        public String getProperty(EnumProp enumProp) {
            return properties.getProperty(enumProp.getKey(), enumProp.getDefaultValue());
        }
    
        public void setProperty(EnumProp enumProp, String value) {
            properties.setProperty(enumProp.getKey(), value);
        }
    }
    

    With this enum:

    public enum EnumProp {
        PROP_1("key", "defaultValue"),
        ...
    
        EnumProp(String key, String defaultValue){
            this.key = key;
            this.defaultValue = defaultValue;
        }
    }