November 8, 2009

Models and Events

Tags:

I have been thinking that software development is all about models and events. By models I mean domain models, and by events I’m referring to an event-driven architecture. Not quite the models and bottles of Investment Banking.

The domain model is where the application’s data lives. It is the model part of the MVC pattern. For example, in a system that manipulates songs, a song would be part of the domain model, together with the song’s name, artist, album etc (in Object-oriented systems there would be a song class containing these attributes). The more time I spend coding, the more I find that the future course of a project is directly related to how its domain model was conceived. Using MVC, changing the model later can involve a great deal of work if the model touches everything else. Thus usually some time is spent on working out the model and refactoring it if necessary. Indeed, I remember once describing a less than satisfying job as drawing pictures all day, meaning UML mainly for the domain (I would have preferred to be coding).

I have a few tips for domain models. Follow the ideal of MVC, that is keep view and controller logic out of the model. Also, try to have fat models and skinny controllers (this is a Ruby On Rails idea, but I find it works well in general). Keep model classes immutable if possible. Lastly, write your own containers (containing and hiding actual SDK-based containers) for easy aggregation functions (and parallelising). None of this is particularly controversial, few people I have worked with would disagree.

What I have recently found surprising is that people do disagree with using an event based architecture where I feel it would work well. Event-driven systems are ones where changes to domain state are packaged as events and passed to listeners of those events through some form of callback. This helps promote a loosely-coupled design, something else I would strongly encourage. Also recommended is keeping the events at the lowest level appropriate in the model (a rule I’ve broken a few times). For instance, if you have an album which contains songs, a “songAdded” event would go on the album listeners, but a “songUpdated” event should fire on the song’s listeners. Other people seem to prefer a system of loops polling for changes (or something similar). I find their code far more complicated. Event-driven systems are simple to write, simple to understand and you only need to handle the events you are interested in. I would be interested to hear what other experienced programmers have found works.


comments powered by Disqus