jump table - Function array in Java? -
maybe think in c, don't see solution how solve in java. response server sends string this:
command params <xml...>
the client receives string , extracts command. call function knows how handle command. on c side solution obvious. implemented array command name , associated function pointes, can loop through array , call function.
is there way on java well? don't know call function based on name. see following options:
- do series of
if(command.euqals(command)
- for each command create separate object can store in array (very messy).
- use reflection, can have map function names vs. command names.
are there other options?
the if statements not best imo, @ least allows compiler errors , typechecking. using reflection @ least more elegant because can loop , extend more easily, of course, means can see runtime errors if misstype names.
your second idea idiomatic. use map<string, runnable>
store command names , corresponding code, commands.get(commandname).run()
execute one.
don't afraid of creating classes! may make code start out more verbose, it's easier write class , never have worry again same switch
or if ... else if ...
. if commands ever become more complicated single methods (maybe tostring()
, undo()
...), you'll increasingly glad used polymorphism instead of conditionals.
Comments
Post a Comment