Command Facade pattern

Several weeks ago, Wolfgang asked after a rename command for Hecl. Pretty simple to do in terms of the Hashtable that maps strings to commands, so I added it. However, there was a problem: in order to save space, I’d been grouping commands together in one class, and dispatching on “argv[0]”. A nearly empty class in Java compiles to something like 500 bytes, so mapping one command to one class is not an acceptable practice when you are working, in some cases, with an upper limit of 64K. Dispatching on argv[0] meant treating it as a string, and doing a compare against the command name, which meant hard coding the command names into the classes implementing commands. Try renaming one of those commands and…oops!

I struggled for a bit trying to find an answer I was happy with, and after talking it over on the mailing list, arrived at doing things like this:

A big class that implements a number of commands, with a dispatch method:

static void dispatch(int cmd, Interp interp, Thing[] argv) throws HeclException {

That method then does a plain old ‘switch’ on the cmd int to go to the correct block of code. The code that calls this is simple, and it has to be, because one gets instantiated for every command, and so it’s imperitive that it doesn’t take up much memory:

class MathCmdFacade implements Command {
    private int cmdtype;

    public MathCmdFacade(int cmd) {
        cmdtype = cmd;
    }

    public void cmdCode(Interp interp, Thing[] argv) throws HeclException {
        MathCmds.dispatch(cmdtype, interp, argv);
    }
}

So far, I’m pretty happy with the results. By making the ‘facade’ (I’m not sure it’s really the facade pattern, but… oh well, the name works for me) small, I don’t waste memory. Plopping all the code in the switch statements is probably loathsome to purists, but it makes the code smaller, something that’s never far from mind when working on Hecl. Things are also a bit faster, because we don’t do the string comparisons to dispatch commands either. All things considered, the code isn’t illegible by any means, either. Furthermore, because the new ‘facade’ commands still just implement the regular old Command interface, which means that Proc still works, and that you can still associate a class implementing Command with a string, so that it remains very easy to implement new Hecl commands in Java, and the interface hasn’t changed.

Faster, smaller, backwards compatible, and ‘rename’ works too… life is good!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s