0

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?

AdrianGW
  • 143
  • 1
  • 8

2 Answers2

1

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.

MikeSW
  • 16,140
  • 3
  • 39
  • 53
  • "And you want a handler to explicitly handle only 1 event, SRP" Thanks, that nails it. Following SRP, topics are not necessary and inheritance is probably a violation of this. Thanks! – AdrianGW Jun 24 '14 at 00:13
0

If you really feel like introducing topics, I'd do it through interface inheritance. For instance:

interface IUserEvent : INonTransactionalEvent { ... }

class UserRegisteredEvent implements IUserEvent {
    public Timestamp: TTimestamp;
}

The impact in your code and language would be negligible, you can keep using a generic Publish method accepting INonTransactionalEvent and you can also easily refactor your topics.

jnovo
  • 5,659
  • 2
  • 38
  • 56
  • Thanks a lot for that, interface inheritance didn't cross my mind! I feel the answer below regarding SRP violation more closely answers the question, though. Thanks! :) – AdrianGW Jun 24 '14 at 00:15