Domain events in code

EventStorming allowed us to make useful domain discovery. We gained some knowledge about the domain and managed to visualize it for shared understanding. Commands also appeared on the more detailed model. In this chapter, we learned how to create entities that protect themselves from executing invalid operations and never come to an invalid state. Operations on entities are performed by executing methods, which quite closely resemble commands that we discovered on our detailed model. So this part is more or less clear, but events have never appeared in our code so far.

In fact, you can implement a system using DDD principles and patterns without having any domain events. It might sound strange after spending so much time working with them using sticky notes, but this is a fact. When we execute an entity method, it changes the entity state. This state change is an implicit event. For example, when our system executes the RequestToPublish method of the ClassifiedAd entity,  it will set the entity State property to ClassifiedAdState.PendingReview value. Effectively, this can be translated to "classified ad sent to review" and this is what we wrote on an orange stickie a while ago.

But most of the time, making domain events first-class citizens in the domain model has excellent benefits. There are two primary use cases for domain events that are implemented explicitly as part of the domain model:

  • Allowing one part of the system to inform other parts of the system about its state changes, using Ubiquitous Language and state change details. We already discussed the idea of splitting the system into multiple pieces, and those pieces need to play well together by listening to each other events and execute necessary operations. If a system is built in such a way that different parts of the system react on each other changes, such a system is called a reactive system. We will be discussing reactive patterns in the "Integration with events" chapter.
  • Persisting domain events to get a full history of state changes inside the domain model. Then, the state for any entity can be reconstructed by reading those events and reapplying them to the entity. This pattern is known as event-sourcing, and we will spend a great deal of time discussing it in this book, especially in the "Event-sourcing" chapter. 

These two techniques can be combined, so when we persist domain events, we can also listen to everything that is being written in other parts of the system and execute reactions to those events.

In this chapter, we will be looking at how we can bring domain events to code and how our entity methods can raise them so we can use these events later.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.4.174