I'm writing a program where a user can input something like
add 5 2
or
define foo
Right now the only way I know to handle this input is a bunch of if/else if statements, ie
if(args[0] == "add") add();
else if (args[0] == "define") define();
else print("Command not found.");
Is there a better way to do this, or maybe some sort of data structure/algorithm that's standard for these types of inputs? I'm using Java specifically, but I'd prefer a language-agnostic answer if possible. Thanks!
Design pattern Command can be used for this goals. For example:
abstract class Command {
abstract public String getCommandName();
abstract public String doAction();
}
To define you own function just implement Command class:
class AddCommand extends Command {
@Override
public String getCommandName() {
return "add";
}
@Override
public String doAction() {
// do your action
}
}
then your main class should looks like:
public class Main {
private static Map<String, Command> commands = new HashMap<String, Command>();
private static void init() {
Command addCommand = new AddCommand();
commands.put(addCommand.getCommandName(), addCommand);
}
public static void main (String[] args) {
init();
if (args[0] != null) {
Command command = commands.get(args[0]);
if (command != null) {
System.out.println(command.doAction());
} else {
System.out.println("Command not found");
}
}
}
You could use a switch statement:
switch (args[0]) {
case "add":
// do your adding stuff
break;
case "define":
// do your defining stuff
break;
default:
// command not found
}
switch is a common feature in most languages (some languages use different syntax, for example Ruby uses case/when instead of switch/case). It only works on Strings starting from Java 1.7 though.
Also, some languages have Dictionarys and functions in variables, so for example in Ruby you could do this:
myDictionary = { "add" => someFunctionToAddStuff,
"define" => anotherFunction }
myDictionary["define"] # returns anotherFunction
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With