I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5). There are at least 20 commands, and likely will have more than 50.
I've come up with a couple of solutions:
- one big switch/if-else on commands
- map of commands to functions
- map of commands to static classes/singletons
Each command does a little error checking, and the only bit that can be abstracted out is checking for the number of parameters, which is defined for each command.
What would be the best solution to this problem, and why? I'm also open to any design patterns I may have missed.
I've come up with the following pro/con list for each:
- keeps all commands in one function; since they're simple, this makes it a visual lookup table
- don't need to clutter up source with tons of small functions/classes that will only get used in one place
- very long
- hard to add commands programmatically (need to chain using default case)
map commands -> function
- small, bite-size chunks
- can add/remove commands programmatically
- if done in-line, same visually as switch
- if not done in-line, lots of functions only used in one place
map commands -> static class/singleton
- can use polymorphism to handle simple error checking (only like 3 lines, but still)
- similar benefits to map -> function solution
- lots of very small classes will clutter project
- implementation not all in the same place, so it's not as easy to scan implementations
I'm writing this in Go, but I don't think the solution is language-specific. I'm looking for a more general solution because I may need to do something very similar in other languages.
A command is a string, but I can easily map this to a number if convenient. The function signature is something like:
Reply Command(List<String> params)
Go has top-level functions, and other platforms I'm considering also have top-level functions, hence the difference between the second and third options.