I have controller that executes some commands according to command name, taken from url. The main point is in not to use if and switch clauses. As I know there are ONLY two ways how to do it - 1) command pattern 2) reflection.
//Command pattern
class Controller{
private HashMap<String,Command> commands;
public void executeCommand(String commandName){
commands.get(commandName).execute();
}
...
}
//reflection
class Controller{
public void readCommand(){
....
}
public void executeCommand(String commandName){
this.getClass().getMethod(commandName+"Command").invoke(this);
}
...
}
So the questios:
- Which one is better?
- Is it normal in one application to let developers use one of the methods they want.
- Are there other ways?
execute
? Will that causeexecuteCommand
to try to call itself recursively? Using reflection in this way, where you use a string entered by the user to determine what method name to execute, looks very dangerous. Might as well put a sign on your program saying "Hey, cybercriminals! THIS WAY!!!" – Boon