Refactoring side effects with domain events
We’ve talked about domain events before and spent a great deal of time thinking about them in the EventStorming exercise in the previous chapter. To refresh your memory, a domain event is a domain-driven design pattern that encapsulates a change in the system that is important to the domain experts. When important events happen in our system, they are often accompanied by rules or side effects. We may have a rule that when the OrderCreated
event happens in our system, we send a notification to the customer.
If we put this rule into the handler for CreateOrder
so that the notification happens implicitly, it might look something like this:
// orderCreation
if err = h.orders.Save(ctx, order); err != nil {
return errors.Wrap(err, "order creation")
}
// notifyCustomer
if err = h.notifications.NotifyOrderCreated(
ctx, order.ID, order.CustomerID,
); err != nil {
...