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:

  1. do series of if(command.euqals(command)
  2. for each command create separate object can store in array (very messy).
  3. 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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -