6

I'm looking at domain events, specifically at 2 possibilities:

A. Using "generic" events like that:

public class OrderStateChangedEvent : IEvent
{
  public Guid OrderId { get; }
  public OrderState NewState { get; }
}

then the consumer would figure out the new state and do something. Since I'm using Rx this would be not that hard (and way better than a switch/case):

var subscription = DomainEvents
     .AsObservable<OrderStateChangedEvent>()
     .Where(e => e.NewState == OrderState.OrderCompleted)
     .Subscribe(OnOrderCompleted);

B. Using specific events:

public class OrderCompletedEvent : IEvent
{
  public Guid OrderId { get; }
}

this would lead to way more event classes, which on one hand may get too many, on the other hand event class names contain language and this may be a plus point.

Do you have any recommendations? I'm not experienced with domain events and can't really make a qualified decision here (both seem not to have any major drawbacks)

Lev
  • 309
  • 1
  • 12

2 Answers2

2

This would boil down to whether the "generic" events results in any behaviour. If it merely carries an interesting value as something like a "category" may then a generic event will suffice.

However, if there is any specific behaviour attached to the event and it, therefore, has any specific meaning in the system I would definitely suggest going for a more explicit approach.

Eben Roux
  • 12,983
  • 2
  • 27
  • 48
  • actually yes, there is behavior attached to specific events. with generic events, the subscriber would try to figure out what the behaviour is by itself, so yes more sense to go with specific events - though some tasks like "subscribe to all state machine changes of a certain domain object" would be probably more difficult to do, since these state changes mean different things (order competed, order cancelled, order fulfillment started etc) – Lev Nov 15 '15 at 11:14
  • 1
    Well, it certainly *would* be more tedious to subscribe to many events when you are just data mining. However, there are other techniques one could implement for those scenarios. You *could* publish both a specific and a generic event. If one is using event-sourcing an event processor could pick up the relevant events from an event stream and process using a shared processing method. As always, one would need to be practical about these things :) – Eben Roux Nov 15 '15 at 15:32
  • I just found out I can use contravariant subscriptions, so the I just need to mark the events i'm interested in with an interface. – Lev Nov 16 '15 at 11:48
1

As a general rule of thumb, using the switch statement is often considered a code smell in OO languages.

http://c2.com/cgi/wiki?SwitchStatementsSmell

B. is more explicit and also makes the code even more concise, if I understand it correctly:

var subscription = DomainEvents
   .AsObservable<OrderCompletedEvent>()
   .Subscribe(OnOrderCompleted);
Alexander Langer
  • 2,883
  • 16
  • 18