I use around 1000 properties associated with a specific java.util.Properties which is backed by a file. The main reason for the file is to change them without recompiling the program and to allow users to adjust their according to their taste. Some of the properties are used only in one place in the code, but there are some properties that are used several times in different segments of code and even different classes.
I have recently got the habit of declaring all those properties that are used as a String constants, usually in a seperate interface like this:
public interface AnimalConstants {
public static final String WEIGHT_PROPERTY = "weight";
public static final String RUNNING_SPEED_PROPERTY = "speedInKph";
public static final String HOURS_OF_SLEEP_A_DAY_PROPERTY = "sleepHrs";
...
}
When a class need to access some of the animal properties, I just implement this interface and I have access to all those property constants declared. When I need a specific property I just use the corresponding constant, without thinking what is its exact name (since abbreviations are used often) and, what is more important, the risk of mistyping a property name is eliminated this way. Another advantage is that if I later choose to rename a property to make it more clear to the advanced user who configures those properties), I just need to change that name in the interface where that property constant is declared (and of course the property file), so no need to "search and replace" the entire project. Finally, I can easily check whether the property is being used or not; I just comment it, compile the code and see if there is an error.
However, in spite of all these advantages, I am curious what are the disadvantages of this approach. What interests me the most is the following:
- What impact has this approach (1000 String constants) on the String pool? Or they are created on-demand when I access those constants? Does this prevent other Strings from being cached in the String pool?
- What is the performance cost of this approach compared to the one where I use hard-coded String constants, is it the same (neglecting the cost of accessing field)? Does the String pool behave similarly or a lot different?
- What's the average memory increase with this approach, are all those String constants kept in memory all the time?
Any good comment/observation is welcome.