Search code examples
eventsdomain-driven-designdomain-eventseda

Domain Events require class or a topic?


Should domain events be dispatched according to event classes, or classes and a topic?

For example, I have the following event:

class UserRegisteredEvent implements INonTransactionalEvent{
    public Timestamp: TTimestamp;
}

And an event manager,

class EventManager {
   /** Omitted **/
}

Udi Dahan proposes that events are first class objects, and I like that. There is a UserRegisteredEvent object, an OrderComplete object. My question is, does the type itself get bound to the event handlers? For example, should I just pass the event object to the publish method?

EventManager.Publish(new UserRegisteredEvent(1));

This means each handler is bound to a single class type, which seems limiting. While YAGNI may be true, is the following not more powerful:

EventManager.Publish(new UserRegisteredEvent(1), Events.UserRegistered)

Whereby the event topic is what the handlers bind to. This way, handlers can benefit from inheritance. If type safety or usage of a ubiquitous language was an issue, one could do:

EventManager.UserRegisteredEvent(1)

Which is simply a short method to the longer publish version. This annoys me a little, as it means the class must be altered for every new event, which seems unnecessary (and indeed, not necessary if using the above method).

While I've only seen events get published as classes with no topic, is this limiting, or has anyone run into issues with this?


Solution

  • Domain events don't really require a specific implementation. After all they are just semantic DTOs. I don't understand what you're trying to accomplish, but unless you're building a service bus you just send the event object to be handled by whatever handlers are configured.

    The Event doesn't know about the handlers, the handlers don't know about each other, the bus knows how to send the event to the handlers. And you want a handler to explicitly handle only 1 event, SRP . You can combine implementations of related handlers into one class, but that's an implementation detail.