Dan Donahue bio photo

Dan Donahue

Musician. Traveler. Programmer.

LinkedIn Github Stackoverflow

One of the patterns I've fallen in love with since starting to use a service bus is the Command Handler pattern. It exists in most distributed messaging bus platforms. However, it's not solely useful in that context. I can only speak for myself here, but I find that programming with discrete commands makes everything much more understandable than service classes. When you have an explicit command for each action in your system, you know exactly where to look for any change.

The pattern is so simple as to be almost laughable. Isn't that often the case with patterns? Take a look at the interface:

But that simple interface gives you so much. I'll delve into just some of the benefits that I've seen.

You know that refactoring called Introduce Parameter Object? The one where you take a long list of parameters to a method and turn them into an object so you can pass that object into the method? Voila! That's the programming model by default for your command handler. Your command is the parameter object. The handler is the method. The pattern enforces that model.

Once you have a common interface for all of your command handlers, you can do things like chain them with ease. So you need to authorize before you take an action? Or audit after an action? Simply create another handler to decorate your main handler:

And the last line of that gist can get even simpler. You wouldn't normally have to manually wrap each handler when you initialize. If you use an IoC container, you can tell it to wrap certain handlers as part of retrieving an instance of the object from the container. By the way, this is called the Open/Closed Principle. You do not modify the existing functionality of a class in order to add new functionality.

Using command handlers also provides a level of abstraction between layers in your application. Take an MVC application or a thick-client application for example. In most applications, when you take an action (submit a form, click a button, whatever), you will either instantiate the domain object directly in your MVC/presenter code or, to be a little cleaner, you'll make a service class that you push those calls to. Those service classes are an abstraction, but they're more tightly coupled than commands. Those classes are usually either per-controller/presenter so they're strongly tied to your front-end framework or they're per-domain object so they're tied to your domain model. With command handlers, you don't have as strong a dependency on a service or domain object. You have a dependency on some sort of infrastructure piece that routes your commands to their respective handlers. This can be a bus, either distributed or in-memory. It's also very easy with either an IoC container or reflection to write code that finds the handler for a given command type and invokes it. In all cases, those are infrastructure pieces, not domain pieces. The common rule is that it's preferable to have dependencies on infrastructure or framework components to the more highly specialized portions of your application such as the domain.

One thing that often comes up in regards to command handlers is the fact that they can't return data, so perhaps they're not as useful as they're touted to be. Quite the contrary - that's a feature, not a bug with the pattern. What a command handler provides is very specific. It's the action taking side of the system. The querying/database reading side should be handled by another mechanism. This follows the CQRS, or Command-Query Responsibility Segregation, principle. You can read about that all over the web - Google CQRS.

What you often see in most applications, are "domain models" that are responsible for both the reading of data and acting on that data. CQRS proposes that it's too much concern for the domain model to handle. Domain models are about enforcing business rules, so it makes sense to have them serve that purpose and not encumber them with reading data. Additionally, querying data has different reasons to change than the business rules. When you're querying, you often want to show large swaths of data via JOINing tables and aggregating, etc. When your domain model is responsible for both reading and writing, you often create your domain model with a lot of relationships so that you can traverse your model and get all the data you need to display. That makes the domain model larger than it needs to be.

When you get down to it, the reasons that read side code changes and the reason that write side/business logic code changes are vastly different. Zipping those up into one model causes the model, and therefore both sides, to suffer. So it's best to break them up. Make a set of read side objects that are optimized for querying. You can make this as loose- or as fine-grained as it needs to be for your querying concerns. On the other end, use your domain model strictly to enforce business rules and use the command handler pattern to call actions in your domain model. A common rule of thumb is that your domain model should be behavioral (i.e. you call methods that change its state) and not queryable.

Even without a full-fledged domain model, I've found command handlers to be a very accomodating mental model for programming. Since there is a discrete handler for each action you can take in your system, it becomes quite easy to find the one you're looking for and to understand what it's doing once you've found it. It's not inconveniently grouped up with a bunch of other methods that don't relate to it at all as is the case with service classes. It's sole reason for existing to perform that one command. And since I've beaten you over the head with best practice talk in this post - that one is called Single-Responsibility Principle. Perhaps the most important of the SOLID principles.

So hopefully this sheds some light into the benefits of a very simple handler implementation. As always, if you have questions/comments/etc., leave them below.