Dan's posterous

« Back to blog

Component Software

 

Advance apologies for bad formatting - seems posterous isn't the greatest for formatted text!

Clojure makes a lot of things really easy. Just for fun, I implemented a simple system for constructing a component based software architecture where each component runs completely independently and asynchronously. Components communicate by sending events to each other, achieving a flat software hierarchy.


We can test this by creating and running some test components:

Comp1 contains three event handlers - :init, :print and :set-msg. Comp2 only contains two event handlers - :init and :print.
:init is called to setup the components state and trigger any initial events. :print will print the contents of the states :msg slot to the terminal and :set-msg will change the :msg slot to the value of the events message.

Running this sample will output the following:

 Ho
 Hello 

It becomes more interesting if the components do a little more, for example:

Running this will output:

 Hi
 Hello
 Ho
 Hello 

Note how the first event gets processed before the secod one - ie, Comp1's :msg has not yet been modified.

Of course, you can set up all sorts of crazy chains of events with many event types, complex logic and so on.

What would be really nice is a DSL designed for writing these component-based programs, since calling run-components and make-components manually is a little messy. Something like the following would be nice:

Luckily, this is the kind of thing Lisp is good at and Clojure, being a Lisp dialect, has everything we need to make it happen:

These macros transform our convenient little DSL into a set of calls to run-components and make-components. Success! We can now write fun little component-based programs, arranged in a flat hierarchy, using an anonymous (sender never knows who receives the events; receiver never knows where the events come from) event-based messaging system.