Search code examples
javadesign-patternsstrategy-patterncommand-pattern

iterating through list of commands to execute- which pattern?


I have written a Java program that reads in a file containing commands to execute(in a language I made up myself). The commands are read in as strings and put into an array. Now a "dispatcher"-method will loop through the array, interpreting the commands and calling the respective methods which will act upon them.

This of course leads to a big block of nested if-statements:

if commandReadIn == this, do that... 
if commandReadIn is of type x, get next element,treat next element as argument... 
etc. 

Right now I only have a handful of commands, but what if I wanted to add hundreds? The code would become unmaintainable.

Now I'm wondering if it's possible to completely get rid of the conditional logic. The command pattern doesn't seem to be of much use here, since I would have to interpret the strings at some point anyway.. which means lots of nested "if"s. If it's not possible, what would be the best approach of restructuring the commands and their grammar in a way that will make it easy to add, edit or remove commands?


Solution

  • Use the Command Pattern for your commands. Your implementation can be greatly simplified.

    1) Create a Command interface with an execute method.
    2) Create an implementation for each command.
    3) When you start your program, create a map of command string -> command implementation.
    4) When you read in a string, look up the appropriate implementation and invoke it.
    5) Optionally, your execute method can take a custom Context object as an argument, allowing you to pass your command arguments in a generalized way. It's up to the implementations to understand the context object and retrieve arguments off it.

    With this approach, you will have no if statements, except possibly a check to see if you failed to retrieve anything from your cache of command implementations.