CompositeCommand – a nice piece of code

Found a nice piece of code recently.

I ran across an article the other day on the Adobe Flash Developer Center site called “Guidelines for Flash application development” written by Andrew Guldman of Fluid. It runs through a whole bunch of suggestions for developing Flash applications, not only from the code point-of-view but also in terms of how developers/designers should interact, organizing and preparing, etc.

The article also offers a free bit of code that the guys at Fluid use to implement a composite command pattern. It’s pretty well abstracted (3 interfaces and 2 interface-implementing classes). Without going into any code, the cool result of it is that you can create a CompositeCommand object which will store any number of asynchronous or synchronous commands. Then, you can execute the series of commands as one batch execution (hence a composite command) and get an event dispatched back when the entire series of commands has run.

Now, the code for this isn’t all that difficult to imagine. It involves an array of stored commands, a few interfaces to implement asynchronous and synchronous commands, a way to begin execution of the commands, and a dispatched event for completion of the entire composite command.

The code is lightweight and abstracts away a very common problem. It’s often the case where we need to do a bunch of initialization to our Flash applications that really becomes a queue of asynchronous/synchronous event calls…An XML file needs to be loaded here which triggers a few movieclip assets to render with data, which starts some additional loading of secondary data from a web service, which creates more clips here, etc. etc. We end up having callback functions or event dispatches that do nothing more than tell the receiving end that we’re ready to fire off another event. And, even worse, we end up with a whole messy path of code to get from the beginning to the end of the initialization process.

CompositeCommand gets rid of having us hand-tie the events together, and what’s especially nice is it doesn’t care whether the events run asynchronously or not. It’s sort of like an automated Rube Goldberg machine where all you really care about is flipping the switch and seeing the milk pour into the cup a minute later. All that stuff involving the electric fan, falling dominoes, and the re-wired lawn mower engine in the middle is hidden from sight.

Simple code to solve a recurring programmatic nuisance.