Sunday, February 14, 2010

Option Explicit On – Commands in CQRS

The idea behind commands in a CQRS architecture is that they should be very explicit and very specific about their intention. You would try to shed away from generic CRUD operations and rather try to capture the essence of what the user is trying to accomplish. Meaning; instead of a ‘one form to save all data’ you would rather let the user explicitly tell what (s)he wants to achieve.

Ok, example. Say you have an application for car dealers. In here you have the possibility to set the price of the car you want to sell. Now, you can either put this as a ‘price field’ among a bunch of other car related data like registration number, brand, model, horsepower, etc, and save it along the rest of the data. Or you can make sure that the changing of a car’s price is a operation of it’s own.

In CQRS you would typically go for the second option. You would make sure that the user’s intent is expressed very explicit by giving this operation it’s own command. That is; instead of putting it inside some big SaveCar method, you make it a method of its own. Something like ChangeCarPrice, or even LowerCarPrice and RaiseCarPrice.

Wouldn’t that be an awful lot of commands, you say? Will you be making a command for every change of value in the application? Hell, no. That would be a lot of commands. And that’s why we don’t do that. We’re making a specific command for ‘car price’ value because the change of this very value is something that has a specific meaning in this domain.

Lowering the price of car is probably an action you need to do because nobody is willing to pay the price you set earlier on. And it can be one of several other marketing actions you can take in order to make the car more saleable. Adding more equipment or freshening up the sales description can be other ‘marketing actions’.

Tracking these specific actions can be very valuable for the car dealer, because having a car taking up space in your warehouse for a longer period of time is bad for profit. Having cars in stock for a minimum amount of time is good for profit. And so tracking which marketing actions that are most effective over time can be very lucrative for a car dealer (or any kind of dealer I guess).

Behave!

Another way of looking at commands is that they should capture the behavior expressed in your domain model. Patterns like Table Module are arguably more focused on data than behavior, which makes them very well suited for systems where complexity is not that high. And contrary for complex domains; Domain Model is more focused on behavior and less data centric.

I would argue that your average Customer Relationship Management system (CRM) or Content Management System (CMS) are examples of systems were data is more important, or rather more valuable, than the behavior of the system. As to all things in life there’s exceptions, but from my own experience the typical CRM and CMS system would make a good fit for a Table Module or Record Set pattern.

Systems built using data centric models are far easier to build and maintain. That is off course until you start having too much logic – too much behavior – sprinkled around the code. In that case you’re probably better off using using something like the Domain Model pattern.

So let’s focus on the Domain Model again, because in a CQRS architecture there will typically be a Domain Model that contains the essential business logic. The core of the business so to speak.

In a sufficiently complex system there will be a lot of behavior and complex rules attached to those behaviors. Let’s take for instance the aforementioned ChangeCarPrice. Larger car dealers can have hundreds of cars for sale, and all cars will have a designated ‘responsible salesman’. Each salesman can have several cars which they are responsible for and they probably will have some kind of bonus arrangement tied to how many cars they sell.

Imagine a scenario where a potential car buyer walks into the shop. Let’s call our potential customer ‘Johnny’.  Johnny has some preferences to what car he want, but for the most part he’s pretty open to which exact car he’ll end up buying. He’s looking for a 4x4 station wagon, preferably black or dark gray, with diesel engine and leather seats. Johnny’s got about $50.000 to spend on the car - which by the way is a mid-priced car here in Norway. (Yes, I know. It’s an expensive country and everything cost more than it should and blah, blah, blah. It’s a whole other story.)

The salesman of this story, let’s call him Bob, doesn’t have any cars that fits within Johnny’s preferences. At least non that appeals enough to make him leave his $50.000 in the shop. Johnny did however spot a BMW at $55.000 that he really liked, but the extra $5.000 is more than Johnny can afford at the moment. And Bob is not willing to let the BMW go for as little as $50.000, so no business is done.

4 weeks go by and the BMW is still in the shop, but now it’s starting to be costly to having it just standing there, and so the price is lower to $50.000. Wouldn’t it be nice if the Bob’s software were smart enough to notify Johnny about this event?

Yes, it would, but building a system that can handle these kind of events is actually very tricky. Having an explicit command that triggers when the car price changes makes it a whole lot easier to add a business rule like ‘notify customer if price drops to or below $50.000’, because you know exactly were to put that behavior.

If you have a system where business logic has been randomly added from the UI all the way down to the database, this will be a lot tougher job to get done.

So what about the CRUD?

I believe you can still have your ‘store these 30 fields to the database’-operations in a domain driven CQRS architecture. You can have your SaveData command. But commands like that, CRUD commands, were you don’t care about anything but persisting the data, will not trigger any behavior in you domain model. They will just persist data into your relational database, file system, blob storage, or whatever medium that holds your data.

Then when new requirements arrive and you need to attach behavior to some of the data in that SaveData command, you will just extract those properties out into their own command and you make that new behavior explicit.

Maybe even all the way from UI and down to the domain model. That way you will capture the user’s intent and you will have means to encapsulate that precious domain knowledge inside your model.

Further Reading

For more background and resources on CQRS you can take a look at my previous post “Growth is optional. Choose wisely.”.

I mentioned the Domain Model, Table Module and Record Set patterns and there’s no better way to learn about these – and other patterns – than to read Martin Fowler’s excellent “Patterns of Enterprise Application Architecture”. A short description of the patterns can be found in the P of EAA Catalog’s "Domain Model", "Table Module" and "Record Set".

I also touched Domain Driven Design a bit, and again; No better source than the source itself. If you haven’t already – go read Eric Evans “Domain Driven Design – Tackling Complexity in the Heart of Software”. Just do it. And you can come back and thank me for the tip afterwards :)

No comments: