Your second idea is idiomatic. Use a Map<String, Runnable>
to store the command names and corresponding code, then commands.get(commandName).run()
to execute one.
Don't be afraid of creating classes! It may make your code start out more verbose, but it's much easier to write a class and never have to worry about it again than to do the same with a switch
or if ... else if ...
. If your commands ever become more complicated than single methods (maybe toString()
, undo()
...), you'll be increasingly glad that you used polymorphism instead of conditionals.