Domain Driven Design: Commands and Events Handlers different responsibilities

Event Sourcing

“Commands have an intent of asking the system to perform an operation where as events are a recording of the action that occurred…”
Greg Young, CQRS Documents Pag. 26

In this post I’d like to state something that I’ve just recalled from a Greg Young’s video. When I started creating an aggregate root I often ask myself… where do I put this logic? where do I have to set these properties? Is the Command or the Domain Event Handler responsible?

As we know, an aggregate root can be considered a boundary for a relevant business case. The public interface of an aggregate exposes behaviours and raises events.

Commands and Events responsibilities

Commands and Events responsibilities

With this in mind, when we design an aggregate root, we start adding behaviours/commands to it and then apply events. The following is a list of what a Command and a Domain-Event handler can and cannot do.

A Command handler is allowed to:

  • Throw an exception if the caller is not allowed to do that thing or passed parameters are not valid
  • Make calculations
  • Make a call to a third party system to get a state or any piece of information

A Command handler is not allowed to:

  • Mutate state (state transition in commands can’t be replayed later applying events)

It behaves like a guard against wrong changes.

A Domain Event Handler is allowed to:

  • Mutate state

A Domain Event Handler is not allowed to:

  • Throw an exception
  • Charge your credit card
  • Make a call to a third party system to get a piece of information
    (logic here can be replayed any time… for example your card can be charged any time you replay events)

They apply the required changes of the state. No validation, no exceptions, no logic.

For example, if we have a command handler method called Deposit that receives an amount of money and updates the balance, we can implement a simple algorithm in the method and raises an event MoneyDeposited with the result of the calculation and any other information that we want to keep stored in our event store.

Example:

public void Deposit(decimal quantity, DateTime timeStamp, Guid transactionId, bool fromATM = false)
{
  if (quantity <= 0)
    throw new Exception("You have to deposit something");
  var newBalance = balance + quantity;
  RaiseEvent(new MoneyDeposited(newBalance, timeStamp, ID, transactionId, fromATM));
}
private void Apply(MoneyDeposited obj) 
{
  balance = obj.NewBalance;
}

Hope this helps

Leave a Reply

Your email address will not be published. Required fields are marked *