I have a class that reads a configuration file once and puts all the parameters (key/value pairs) in a Map.
For retrieving values from the Map instance I have created a method that takes a key and return the corresponding value.
The config map is passed to all the classes that need to read from the configuration. Each class that uses it reads the configuration parameters it needs and stores them in instance variables which are referred to in the rest of the class.
Is it correct to use an instance variable and store the value in that or should I call the accessor method on the config object whenever I am required to get the value for any key?
First, your configuration class should consider using
java.util.Propertiesfor its loading (and saving if necessary.) It’s very convenient.Second, what you’re doing is dependency injection, which is a good thing. You make it clear that “This class uses –THESE– configuration settings.” I think what you’re doing is right.
It sounds like you’re caching these values in your class rather than looking them up from your configuration. That’s fine under the following conditions
Example of two:
In any event, this is why you only reference instance variables in your get() methods and always use get() methods, even in internal methods.
Consider the internal workings of MyClass
Now let’s say you want to change the implementation of MyClass so it references a MyProps instance so it can change on the fly (as in, #2 above doesn’t apply, you want to change behavior as you go
The class would have been better from the start if we made our class use the getter method, even if it’s private. Getters do not need to be public if you don’t want
This way when we go to change the behavior to be not cached, but instead dynamic to the props file, we can do this:
Now granted, this was a small example with one instance. Most of your classes will have 20 or 30 places where you’d have to change it. This makes it much easier to refactor your code, even if the getters are private.