Thursday, June 18, 2015

The Dispatcher pattern

We recently (last few years) started using the dependency injection in most of our classes. This is fun but can result in a lot of maintenance work.

I recently discovered that building a face for outgoing events from the handlers can reduce the number of interlinks by a factor of three or four. Before, each class tended to need a reference to most of the following: sending messages out, sending messages back, queueing new tasks, and accessing the database. Writing a unit test involved mocking all of these objects.

The alternative that we are now using is to have a single class (the dispatcher) that holds these references and provides functions for sending (sync or async depending on the situation) messages to them. This means that the large number (usually 10 or more) of handlers each only need a single reference to the dispatcher, and when writing a test, we usually only need to mock the dispatcher.

Much better!

No comments: