DDD: Refactoring toward deeper insight

A good question came up on the DDD/CQRS group earlier today, and I thought I’d publish my response here.

The questioneer was asking how they should model deletions in their domain, where they might have a “Delete[Entity]Command”.

If you read Eric Evans’ DDD book, you’ll find it often talks about “refactoring toward deeper insight“. This basically means when you’re not sure which way to go when modelling the domain that you should go back and talk to your domain experts. Keep talking as the information soaks in and you’ll find yourself picking up on little seemingly throwaway phrases and bits of information here and there. They don’t think are particularly special because they’re so used to them, but to you these little facts are incredibly important. It’s like panning for gold.

In this case, “delete” might not be a use-case your domain experts need. In fact, unless your domain experts are in the domain of computers and file systems, I’d go as far as to say it’s highly unlikely. A Domain Model is just that – a model of the domain. Since most domains are in the real world, “delete” doesn’t really exist. You can’t “delete” a stock item, or a financial transaction. You can perhaps mark a stock item as “lost” or create a reciprocating financial transaction though.

Take an example of sales orders (modelled by a SalesOrder AR). If you ask your domain experts “what happens when you delete an order?” they’ll likely respond “Oh no – you can’t delete orders!”. You explain that’s not quite what you meant, and discover that orders can be “cancelled” or “completed”, in which case you can’t add any more line items.

In this example “completed” and “cancelled ” are the key words, and you’d implement the appropriate invariants in your SalesOrder aggregate root (AR). Of course that implementation may end up as a state machine, but then it’s often the case that an AR works like a state machine (i.e. favour a variable “state” rather than a heap of boolean flags).

In fact in general you should be wary of terms like “create”, “update” and “delete” when modelling your domain. If these are the only verbs in your ubiquitous language you should probably not be using DDD for that system.

Remember that DDD is allowing the Domain to Drive your Design. The Domain Experts know it best so they’re your best tool. Your domain model should reflect behaviours and rules required and defined by the domain experts and only those behaviours and rules.