There are different ways to set a member variable from a constructor. I am actually discussing how to properly set the final member variable, in particular the map that is loaded by the helper class elements.
public class Base { private final Map<String, Command> availableCommands; public Base() { availableCommands = Helper.loadCommands(); } }
In the above example, the helper class is as follows:
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 it is better to use a method to set such a variable in the constructor. So, the base class will 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 can not save the final modifier and get a compiler error (the final variable cannot be set)
Another way to do this:
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 Helper class method 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 I can create a new map using new HashMap<String, Command>(); ? . My main question is: if there is a recommended way to do this, given that some functions come from this helper static method, how is the way to load the actual map using records?
Create a new map in a base class or Helper class? In both cases, Helper will actually load, and the base link to a map containing specific commands will be closed and final.
Are there even more elegant ways to do this other than the options I'm considering?