There are different ways to set a member variable from the constructor. I am actually debating how to properly set a final member variable, specifically a map which is loaded with entries by a helper class.
public class Base {
private final Map<String, Command> availableCommands;
public Base() {
availableCommands = Helper.loadCommands();
}
}
In the above example the helper class looks like this:
public class Helper {
public static Map<String, Command> loadCommands() {
Map<String, Command> commands = new HashMap<String, Command>();
commands.put("A", new CommandA());
commands.put("B", new CommandB());
commands.put("C", new CommandC());
return commands;
}
}
My thought is, that is better practice to use a method to set such a variable in the constructor. So Base class would look something like this:
public class Base {
private final Map<String, Command> availableCommands;
public Base() {
this.setCommands();
}
private void setCommands() {
this.availableCommands = Helper.loadCommands();
}
}
But now I cannot maintain the final modifier and get a compiler error (Final variable cannot be set)
Another way to do this would be:
public class Base {
private final Map<String, Command> availableCommands = new HashMap<String, Command>();
public Base() {
this.setCommands();
}
private void setCommands() {
Helper.loadCommands(availableCommands);
}
}
But in this case the method in the Helper class would change to:
public static void loadCommands(Map<String, Command> commands) {
commands.put("A", new CommandA());
commands.put("B", new CommandB());
commands.put("C", new CommandC());
}
So the difference is where do I create a new map with new HashMap<String, Command>();
? My main question is if there is a recommended way to do this, given that part of the functionality comes from this Helper's static method, as a way to load the actual map with entries?
Do I create the new map in my Base class or the Helper class? In both cases Helper will do the actual loading and Base's reference to the map holding the concrete commands will be private and final.
Are there perhaps other more elegant ways to do this besides the options I am considering?