Developing a command processor

Our first attempt to implement a command process that may look similar to the following:

function process_command(command::String, args)
if command == "open"
# open a file
elseif command == "close"
# close current file
elseif command == "exit"
# exit program
elseif command == "help"
# pops up a help dialog
else
error("bug - this should have never happened.")
end
end

The process_command function simply takes the command as a string. Then, depending on the value of the string, it will call the respective function. The args argument may be passed by the GUI code for additional information; for example, the path of the file that is being opened or closed.

There is nothing wrong with this code from a logical perspective, but it can be improved, as follows:

  • The code contains a list of if-then-else statements. In this example, we only have to support four functions. In practice, we will probably have to handle many more functions. Having such a large if-then-else block makes the code very ugly and hard to maintain. 
  • Whenever we need to add a new command, we have to modify this function to include a new condition.

Fortunately, we can make it better using singleton types and dynamic dispatch. We'll go over that next.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.114.38