Maybe I think to much in C, but I don't see a solution how to solve this properly in java. I get a response from my server which sends a string like this:
command params <xml...>
The client receives that string and extracts the command. Now I would like to call a function which knows how to handle the command. On the C side the solution is obvious. I implemented an array with the command name and associated function pointes, so I can simply loop through the array and call the function.
Is there some way to do this on Java as well? I don't know that I could call a function based on the name. So currently I see the following options:
- Do a series of
if(command.euqals(COMMAND)
- For each command I could create a separate object which I can store in an array (very messy).
- Use reflection, so I can have a map with the function names vs. command names.
Are there any other options?
The if statements is not the best IMO, but at least it allows for compiler errors and typechecking. Using reflection is at least more elegant because I can loop and extend it more easily, but of course, it means that I can see only runtime errors if I misstype the names.
Your second idea is idiomatic. Use a
Map<String, Runnable>
to store the command names and corresponding code, thencommands.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
orif ... else if ...
. If your commands ever become more complicated than single methods (maybetoString()
,undo()
...), you'll be increasingly glad that you used polymorphism instead of conditionals.