Friday, January 27, 2012

System.Collections.IEnumerable and collection initializer syntax

I'd like to make a post about something that I think is one of the least utilized aspects of C#: custom collection initializers. Implementing a custom collection initializer for your class can make your code much more declarative and concise.

It's common to have a collection of things that you set up at design time: drop down list items, configurations, items in a game, a list of mappings, all kinds of things. These are often stored in external xml files or in a sql table. If you're like me then you'd rather have this in code and have it as concise and easy to get right as possible. Here's how.

Look at this example of setting up a list of Armor types for a game:

public List<Armor> ArmorsWithListExample()
{
 List<Armor> armors = new List<Armor>();
 armors.Add(new Armor("leather armor",  1,  250, 10));
 armors.Add(new Armor("chain mail",     4,  500, 14));
 armors.Add(new Armor("splint mail",    7,  750, 16));
 armors.Add(new Armor("plate armor",   10, 1000, 18));
 return armors;
}

Here is the same thing using the collection initializer syntax:

public List<Armor> ArmorsWithInitializedListExample()
{
 return new List<Armor>() {
  new Armor("leather armor",  1,  250, 10),
  new Armor("chain mail",     4,  500, 14),
  new Armor("splint mail",    7,  750, 16),
  new Armor("plate armor",   10, 1000, 18),
 };
}

There are several advantages with the collection initializer syntax. You don't have to have the temporary variable, it's less code with fewer redundancies, and it's a nice declarative way to show that all you are doing is creating the collection. Small advantages, I admit, but they add up. But if you look at some C code, you see that the code can be even more concise by declaring the objects themselves inline. Here's an example from the game Brogue:

const itemTable armorTable[NUMBER_ARMOR_KINDS] = {
 {"leather armor", "", "", 10, 250,  10, {30,30,0},  true, false, "This lightweight armor offers basic protection."},
 {"scale mail",  "", "", 10, 350,  12, {40,40,0},  true, false, "Bronze scales cover the surface of treated leather, offering greater protection than plain leather with minimal additional weight."},
 {"chain mail",  "", "", 10, 500,  13, {50,50,0},  true, false, "Interlocking metal links make for a tough but flexible suit of armor."},
 {"banded mail",  "", "", 10, 800,  15, {70,70,0},  true, false, "Overlapping strips of metal horizontally encircle a chain mail base, offering an additional layer of protection at the cost of greater weight."},
 {"splint mail",  "", "", 10, 1000,  17, {90,90,0},  true, false, "Thick plates of metal are embedded into a chain mail base, providing the wearer with substantial protection."},
 {"plate armor",  "", "", 10, 1300,  19, {120,120,0}, true, false, "Emormous plates of metal are joined together into a suit that provides unmatched protection to any adventurer strong enough to bear its staggering weight."}
};


It's a small improvement but I want to do that in C# as well. With custom collection initializers, you can.

public List<Armor> ArmorsWithCustomInitializerExample()
{
 return new ArmorCollection() {
  { "leather armor",  1,  250, 10 },
  { "chain mail",     4,  500, 14 },
  { "splint mail",    7,  750, 16 },
  { "plate armor",   10, 1000, 18 },
 }.List;
}

Look at that! Concise and easy to get right. Here's the code for the ArmorCollection; notice that it's just a wrapper around a List. The only additional functionality it has is the Add method.

class ArmorCollection : IEnumerable
{
 public List<Armor> List { get; set; }
 
 public ArmorCollection()
 {
  List = new List<Armor>();
 }
  
 IEnumerator IEnumerable.GetEnumerator(){
  return List.GetEnumerator();
 }
  
 public void Add(string name, int weight, int cost, int ac)
 {
  List.Add(new Armor(name, weight, cost, ac));
 }
}

The Add method is what makes it work. According to section 7.6.10.3 of the C# specs, if a class implements the IEnumerable interface then the compiler converts the initializer syntax into a series of calls to the Add method, even though the Add method isn't part of the IEnumerable interface. The Add method can have any number of parameters and the compiler will make it work.

So when you have a collection of things that isn't going to change, instead of using a built-in collection with a series of Add calls, loading from an external xml file, or loading a sql table, consider creating an in memory collection by using a custom initializer: it may be easier, faster, and more concise than the alternatives.

Tuesday, January 24, 2012

My summary of CQRS and DDD

Recent epiphany: sagas are just ways to turn domain events into commands.

Here's my as-of-now summary of the concepts I see in many EventSourcing, CQRS, and DDD videos and blog posts.

Command: A simple message that represents a user's request to make something happen. Just data with no behavior and often named in the imperative tense.
class CloseAccount implements Command
{
  public AccountId accountId;
  public String reason;
 
  public CloseAccount(AccountId accountId, String reason){
    this.accountId = accountId;
    this.reason = reason;
  }
}

CommandHandler: A domain service that turns a command into events by calling methods on an aggregate root, publishes the resulting events, and handles transactions and persistence. Stateless with just behavior; just a task based method and sort of procedural.
class AccountCommandHandler extends CommandHandler
{
  private AccountRepository _repository;
  private MessageBus _messageBus;
 
  public AccountCommandHandler(AccountRepository repository, MessageBus messageBus){
    this._repository = repository;
    this._messageBus = messageBus;
  }
 
  public void handle(CloseAccount command){
    Account account = _repository.get(command.accountId);

    account.close(command.reason);
  
    persistAndPublishEvents(account);
  }
}

Aggregate Root: A persistent domain object that turns method calls into domain events. May contain references to other domain objects as part of a parent/child relationship. Stateful and behaviorful and guaranteed to be internally consistent.
class Account extends Aggregate
{
  private AccountId id;

  public Account(AccountId id){
    this.id = id;
    super.storeEvent(new AccountCreated(this.id));
  }

  public void Close(CloseReason reason){
    super.storeEvent(new AccountClosed(this.id, reason));
  }
}

Domain Event: A simple message that represents a change to the state of an aggregate. Just data with no behavior and often named in the past tense.
class AccountClosed implements DomainEvent
{
  public AccountId accountId;
  public CloseReason reason;
 
  public AccountClosed(AccountId id, CloseReason reason){
    this.accountId = id;
    this.reason = reason;
  }
}

MessageBus: A mechanism for publishing commands and events and subscribing handlers to commands and events. May be a separate EventBus and CommandBus. The only behavior is publishing events and subscribing event and command handlers to events; the only state is what's required to track which services have subscribed to which events.
public class SimplestEventBus implements EventBus
{
  private List<Handler> handlers = new ArrayList<Handler>();
  
  public void subscribe(Handler handler)
  {
    handlers.add(handler);
  }
  
  public void publish(DomainEvent event)
  {
    for (Handler handler : handlers)
      handler.handle(event);
  }
}
Saga: A persistent object that turns domain events into commands. Stateful and behaviorful. The only state is what's required for knowing when to create the commands.
// Send a notice to the account's owner once the account is
// both paid off and closed. (ignore thread safety since this is a simple example)
class OwnerNotificationSaga implements Saga
{
  private AccountRepository _repository;
  private MessageBus _messageBus;
 
  private List<Account> closedAccounts = new ArrayList<Account>();
  private List<Account> paidOffAccounts = new ArrayList<Account>();
 
  public OwnerNotificationSaga(AccountRepository repository, MessageBus messageBus){
    this._repository = repository;
    this._messageBus = messageBus;
  }
 
  public void handle(AccountClosed event){
    Account account = _repository.get(event.accountId);
  
    if (closedAccounts.contains(account))
      return;
  
    if (paidOffAccounts.contains(account)){
      sendNotice(account);
      paidOffAccounts.remove(account);
    } else {
      closedAccounts.add(account);
    }
  }
 
  public void handle(AccountPaidOff event){
    Account account = _repository.get(event.accountId);
  
    if (paidOffAccounts.contains(account))
      return;
  
    if (closedAccounts.contains(account)){
      sendNotice(account);
      closedAccounts.remove(account);
    } else {
      paidOffAccounts.add(account);
    }
  }
 
  private void sendNotice(Account account){
    _messageBus.publish(new NotifyOwner(account.ownerId));
  }
}

So, for many of the examples I've seen, a user creates Commands that are handed to a MessageBus that dispatches it to a subscribed CommandHandler. The CommandHandler loads the relevant Aggregate and calls methods on it. The resulting events are gathered, persisted (if doing Event Sourcing), and passed to the MessageBus. The subscribers to that event will often update some read model (effectively turning domain events into updates on report tables) but they may be Sagas that track events and create related commands when necessary.

None of that is the essence of DDD or the essence of CQRS, but it's so common to the discussions and examples that this little glossary helps me to keep things straight.

Tuesday, January 17, 2012

Typefull Dynamic API: a typesafe C# facade/adapter/monad with phantom types

One of the things I came up with at home and actually got to implement at work is so useful, and novel to the C# crowd, that I thought I'd share. I call it a Typefull Dynamic API and it looks like an object that changes its public api at design time based on what would be the state of another object at runtime. Impossible? Nope. I'll even show you how you could have came up with it yourself.

The scenario

Imagine the following fictitious method:
public Account Example()
{
    var account = new Account();
    account.State = UsaState.California;
    account.Open();
    PeopleManager.SetAccountPeople(account, 0);
    MemberLevelServiceHelper.SetAccountHolderLevel(account, MemberLevel.Gold);
    new DebtCalculator().CalculateDebt(account);
    account.Complete();
    Reports.GetCompletedAccountReport().AddAccount(account);
    AccountUtil.Close(account);
    NoteAddingSingleton.Instance.AddNote(account, "I'm an example!");
    return account;
}
It looks like it creates an account, does some setup, and returns it. It's calling a bunch of things from all over the place. I know from experience that I'd have a hard time remembering where everything is and what order to call it in. Some things are on the account, some are singletons, some are helpers and utils - exactly the kind of situation that anyone who's joined a long term project with many other developers is familiar with. If only there was a unified interface for all these subsystems - oh wait - isn't that the definition of the classic Facade pattern?

The patterns

class AccountLifecycleFacade
{
    public Account RealAccount { get; set; }

    public AccountLifecycleFacade() 
    {
        RealAccount = new Account();
    }

    public void SetState(UsaState state)
    {
        RealAccount.State = state;
    }

    public void Open()
    {
        RealAccount.Open();
    }

    public void SetAccountPeople(int count)
    {
        PeopleManager.SetAccountPeople(RealAccount, count);
    }

    public void MakeGoldLevel()
    {
        MemberLevelServiceHelper.SetAccountHolderLevel(RealAccount, MemberLevel.Gold);
    }

    /* ... etc ... */
}
Having this facade lets us work through the lifecycle of an account without worrying about where that functionality is actually implemented; no more trying to remember which helper, manager, singleton, service, utility, or business class to use since we only need to look at one place. With one class for the hi-level functionality, we have a clear api and intellisense will show us what we can do with an account.
public Account FacadeExample()
{
    var account = new AccountLifecycleFacade();
    account.SetState(UsaState.California);
    account.Open();
    account.SetAccountPeople(0);
    account.MakeGoldLevel();
    account.CalculateDebt();
    account.Complete();
    account.AddToCompletedAccountReport();
    account.Close();
    account.AddNote("I'm an example!");
    return account.RealAccount;
}
And since it works with a single account at a time we can make it a wrapper. If we make the wrapper return itself at the end of each method then we'll be able to call it using a fluent interface.
class AccountLifecycleAdapter
{
    public Account RealAccount { get; set; }

    public AccountLifecycleAdapter(Account account) 
    {
        RealAccount = account;
    }

    public AccountLifecycleAdapter SetState(UsaState state)
    {
        RealAccount.State = state;
        return this;
    }

    public AccountLifecycleAdapter Open()
    {
        RealAccount.Open();
        return this;
    }
    /* ... etc ... */
}
And now our example method is a little simpler.
public Account Example()
{
    var account = new AccountLifecycleAdapter(new Account())
        .SetState(UsaState.California)
        .Open()
        .SetAccountPeople(0)
        .MakeGoldLevel()
        .CalculateDebt()
        .Complete()
        .AddToCompletedAccountReport()
        .Close()
        .AddNote("I'm an example!");

    return account.RealAccount;
}
That's much easier for me to read, understand, and test. I'm sure this facade/adapter has been done a hundred times before. I see one potential problem though: it looks like some of the methods are only valid at certain times. I'd wager that you can't complete a non-open account and that you really shouldn't add an account to the Closed Account Report until it's closed. We could rely on runtime assertions to verify the preconditions and post conditions of our new Account api, which is a fine idea, but wouldn't it be nice if we could catch this at compile time?

The magic

If the preconditions and postconditions of these methods were expressed in the type system then not only would the compiler stop us from running invalid code, but intellisence would only show the methods that are valid for the account we have. In order for that to work we need to change the type of our AccountLifecycleAdapter to expose the state of the account. For this example, certain things may only be valid when the account is new, opened, completed, or closed and certain things may only be valid for new, bronze, silver, or gold members. Not only do these methods have preconditions based on the status and member level of the account, but they also have postconditions that change the state of the account.

Some preconditions and post conditions of the domain methods.
MethodPreconditionPostcondition
Open()Status = NewStatus = Open
Complete()Status = OpenStatus = Complete
Close()Status = Open or CompleteStatus = Close
AddToCompletedAccountReport()Status = CompleteStatus is unchanged

Although we can change the state of an object, we can't change its type. Luckily we don't need to since we are returning an AccountLifecycleAdapter with each method: we can return a different type that represents the state of the account and only supports the methods that are valid for that account state.

One possible way is to have a new class for each possible state.
class AccountLifecycleAdapter_NewStatus_NoLevel
{
    public Account RealAccount { get; set; }
    public AccountLifecycleAdapter_NewStatus_NoLevel(Account account) 
    {
        RealAccount = account;
    }

    public AccountLifecycleAdapter_NewStatus_NoLevel SetState(UsaState state)
    {
        RealAccount.State = state; 
        return this;
    }

    public AccountLifecycleAdapter_OpenStatus_NoLevel Open()
    {
        RealAccount.Open();
        return new AccountLifecycleAdapter_OpenStatus_NoLevel(RealAccount);
    }

    /* ... etc ... */
}
This would make sure that the wrapper expresses the state of the account and that only valid methods are called for that account. But it could become a cartesian explosion; this example as 4 statuses and 4 member levels for a total of 16 classes you need to make. Since some things are applicable for several states (like CalculateDebt and Close from our earlier table), they'd need to be implemented in several different wrapper classes. Messy. Fortunately for C# users, the language offers a convenient way out by way of generics and extension methods. Instead of having the class name express the state, we can use a generic type parameter for each run time variable we wish to track; status and member level in this case. A method that creates a copy with the type parameters we want would let us chain the wrapped object along while changing the type parameters.

class AccountLifecycleAdapter<Status, Level>
{
    public Account RealAccount { get; set; }
    public AccountLifecycleAdapter(Account account)
    {
        RealAccount = account;
    }
   
  public AccountLifecycleAdapter<NewStatus, NewLevel> SetTypes<NewStatus, NewLevel>()
  {
    return new AccountLifecycleAdapter<NewStatus, NewLevel>(RealAccount);
  }
}


And a non-generic version will make sure we create the adapter with the correct default type parameters.

public class AccountLifecycleAdapter
{
  public static AccountLifecycleAdapter<New, NoLevel> New(Account account)
  {
    return new AccountLifecycleAdapter<New, NoLevel>(account);
  }
}


The methods that used to belong to the wrapper can now be moved into extension methods.

 public static class AccountLifecycleAdapterExtensions 
 {
  public static AccountLifecycleAdapter<New,NoLevel> SetState(this AccountLifecycleAdapter<New,NoLevel> adapter, UsaState state)
     {
         adapter.RealAccount.State = state;
         return adapter.SetTypes<New,NoLevel>();
     }
 
     public static AccountLifecycleAdapter<Open,L> Open<L>(this AccountLifecycleAdapter<New,L> adapter)
         where L : AccountLevel
     {
         adapter.RealAccount.Open();
         return adapter.SetTypes<Open,L>();
     }
  
  public static AccountLifecycleAdapter<Open,L> SetAccountPeople<L>(this AccountLifecycleAdapter<Open,L> adapter, int count)
   where L : AccountLevel
     {
         PeopleManager.SetAccountPeople(adapter.RealAccount, count);
         return adapter;
     }

    /* ... etc ... */
If we look at our extension methods then we see something I think is very interesting. With this kind of typefull api, the input parameter type represents the precondition and the return type represents the post condition.
public static AccountLifecycleAdapter<Open,L> Open<L>(this AccountLifecycleAdapter<New,L> adapter) 
    where L : AccountLevel
MethodPreconditionPostcondition
OpenStatus = NewStatus = Open

Since the valid status is expressed as a precondition and the what the method changes is expressed as the return type, the compiler and intelisense can make sure you only chain methods that make sense. If a method returns an AccountLifecycleAdapter<Open, Silver> then you can't call an extension method that expects a Closed account. Intellesence won't suggest invalid methods and the compiler won't allow them. As an added bonus, changing the preconditions or post conditions in a way that breaks code will prevent a compile instead of lying dormant until discovered, investegated, and fixed during manual or automated testing.

All we need now are the types that represent the runtime state.

The Phantom Types

These types are a little odd in that they are only used for compile time info and we never create instances of them. The Haskell community would call them Phantom Types so we should too.
namespace PhantomTypes
{
    public abstract class PhantomType {}

    public abstract class AccountStatus : PhantomType {}
    public abstract class New : AccountStatus {}
    public abstract class Open : AccountStatus {}
    public abstract class Completed : AccountStatus {}
    public abstract class Closed : AccountStatus {}

    public abstract class AccountLevel : PhantomType {}
    public abstract class NoLevel : AccountLevel {}
    public abstract class Bronze : AccountLevel {}
    public abstract class Silver : AccountLevel {}
    public abstract class Gold : AccountLevel {}
}
I like to make it double obvious that these are different than normal types with a separate PhantomType namespace and PhantomType base class.

Since the type parameters are part of the method signature, you can have different overloaded methods for different states. Here we can see that an overdraft will close the account unless it's a gold level account; they just get a warning.
    public AccountLifecycleAdapter<S,GoldLevel> Overdraft<L>(this AccountLifecycleAdapter<S,GoldLevel> adapter)
        where S : AccountStatus
    {
        NotificationService.GetInstance().NotifyOfOverdraft(adapter.Account);
        return adapter.SetTypes<S,GoldLevel>()
    }

    public AccountLifecycleAdapter<Closed,L> Overdraft<S,L>(this AccountLifecycleAdapter<S,L> adapter)
        where S : AccountStatus
        where L : AccountLevel
    {
        AccountUtil.CloseDueToOverdraft(adapter);
        return adapter.SetTypes<Closed,L>()
    }
Interfaces can be used if an extension method will work with multiple different phantom types.
  public abstract class AccountStatus : PhantomType {}
  public interface NotNew { }
  public abstract class New : AccountStatus {}
  public abstract class Open : AccountStatus, NotNew {}
  public abstract class Complete : AccountStatus, NotNew {}
  public abstract class Closed : AccountStatus, NotNew {} 
And the method that uses it would add that as a type parameter constraint.
     public static AccountLifecycleAdapter<S,L> AddNote<S,L>(this AccountLifecycleAdapter<S,L> adapter, string note)
         where S : AccountStatus, NotNew
   where L : AccountLevel
  {
   NoteAddingSingleton.Instance.AddNote(adapter.RealAccount, note);
         return adapter;
  }

Where to go from here

A lot more functionality and safety can be added. One idea is to add a check to the adapter's constructor or SetTypes method that asserts the phantom types match the actual run time state. This would let you know if your expectations of what's going on are correct or not.

public void CheckTypes<NewStatus, NewLevel>()
{
    if (typeof(GoldLevel).IsAssignableFrom(typeof(NewLevel)) && RealAccount.MemberLevel != MemberLevel.Gold)
      throw new InvalidOperationException("expected account member level Gold; got " + RealAccount.MemberLevel);
}

Another thing the adapter could do is collect all the ancillary objects that get created along the way. That way, once you're done with it you not only have your account, or whatever you were making, but any other related objects and you won't need to query for them.

One idea I haven't tried (yet...) is generating documentation about the system based on the adapter's extension methods. If you think about it, each of these methods is a transition from preconditions to postconditions. Each precondition and postcondition would be a state. You could use reflection, or old fashioned string manipulation, to capture all of the states and transitions within an adapter and create a state transition diagram. In a complex system this could be very useful for explaining the system to new hires, managers, users, other developers, or testers. Speaking of testing, knowing all of the different states transitions would also help ensure you are adequately testing all code paths.

I'm not entirely sure what to call this construct or "pattern". It's sort of the opposite of the State pattern; instead of an object changing behavior at run time, it's exposing a different api at design time. It's sort of like a Builder since you're building an object through a path that's more complex than a simple constructor. It can be a Facade and call other sub systems, but it doesn't have to be. It's also an Adapter since it exposes functionality related to the wrapped object. In my mind, the important thing is that it this is an adapter that only exposes methods that are valid for the run time state of the wrapped object. For now I'm calling this a Typefull Dynamic API but there may be a better name.

The Summary

Using the facade pattern can greatly aid in readability, understandability, and testability of a complex system with many subsystems - that's been known by many people for many years now. Using an object that returns itself in each method makes fluent interfaces possible - that's been known for a few years too. And using the signature of the method to express the preconditions and postconditions and making sure things are only called on object with the correct state has been around for decades, although I think the object oriented crowd has missed out on a lot of this since you can't change the type of an object when its state is changed. Extension methods give C# developers a chance to combine these in a useful way to get something new: a Typefull Dynamic API that changes its public api at design time based on what would be the state of another object at runtime.

Tuesday, January 10, 2012

The simplest typesafe EventBus

I'm a big fan of typesafety so while exploring messaging and events, I've also tried my own typesafe EventBus:

public static class EventBus
{
  private static Dictionary<Type, List<Action<object>>> handlers 
      = new Dictionary<Type, List<Action<object>>>();
  
  public static void Subscribe<T>(Action<T> handler){
    if (!handlers.ContainsKey(typeof(T)))
      handlers.Add(typeof(T), new List<Action<object>>());
   
    handlers[typeof(T)].Add(e => handler((T)e));
  }
  
  public static void Publish<T>(T e){
    var eventType = typeof(T);
   
    foreach (Type handlerType in handlers.Keys)
      TryPublishForType(handlerType, eventType, e);
  }
  
  private static void TryPublishForType(Type handlerType, Type eventType, object e){
    if (handlerType.IsAssignableFrom(eventType))
      handlers[handlerType].ForEach(handler => handler(e));
  }
}

It's very similar to the simplest event bus. I'm sure there are other ways of tracking what subscribers can handle each event but the Dictionary<Type, List<Action<object>>> works well enough. If you're not used to Haskell or C# type trickery then it may seem too complex either way but I think much of that is caused by how verbose C# tends to be.

One neat thing about typesafe event busses is that, if designed for it like this one is, they can respect the inheritance tree. That means if an Action<object> is subscribed, then it will get everything that get's published since all events are assignable to object. This also means that it is backwards compatible with the simplest EventBus. A few subscribers may need to explicitly state the event type they are interested in but if they use object as the type parameter when subscribing, then the behavior should be the same.

Wednesday, January 4, 2012

The simplest EventBus

I've been playing a lot with event buses, domain events, messaging, or whatever you want to call it. I've seen some open source event buses but they looked pretty complicated and often had a lot of extra baggage that clouded what I was interested in: exploring different ways to decouple collaborating classes. I had enough of that and set out to find the simplest thing that would get the job done and here's what I came up with:
public static class EventBus
{
  private static List<Action<object>> handlers = new List<Action<object>>();
  
  public static void Subscribe(Action<object> handler)
  {
    handlers.Add(handler);
  }
  
  public static void Publish(object e)
  {
    handlers.ForEach(handler => handler(e));
  }
}

That's it. No unsubscribing, multithreading, xml configuration, flexible dispatching strategies, subscription tokens, base classes, interfaces, or attributes. You don't have to use any specific interfaces to subscribe or publish. You don't even have to instantiate it - it's always ready. Anything can subscribe, anything can publish, from anywhere in your project. Anything can be published and every subscriber will get it. Want to publish an AccountClosed domain event? Go for it. Want to publish a naked string or int? Go ahead. How about publishing your entire Windows Form? I'm not sure why you would, but this won't stop you.

Just one line to wire-up a subscription (often called from Main):
public static void AddSubscriptions(ILogger logger, PopulationReport pop, MainApp app)
{
  EventBus.Subscribe(e => logger.Log(e.GetType().Name + ":" + e.ToString()));

  EventBus.Subscribe(app.HandleEvent);

  EventBus.Subscribe(e => {
    if (e is CreatureCreated)
      pop.CreatureCreated(((CreatureCreated)e).Creature);
    else if (e is CreatureDied)
      pop.CreatureDied(((CreatureCreated)e).Creature);
  });
}

And one line to publish (often called from domain objects):
public void Die()
{
  this.health = 0;
  EventBus.Publish(new CreatureDied(this));
}

It can be a bit on the slutty side since it's globally accessible and subscribers will get everything that's published, but that comes with benefits too. This is a good starting point and I haven't had any problems with it: the type checking is minimal for subscribers, I've never tried to subscribe a null, and I don't mind having my domain objects explicitly depend on it. You could add a ClearSubscribers method or a SetInstance method for unit testing, but I just use a single subscriber that dumps all events into a list when a unit test needs to ensure that specific events were created. In the last few at home projects I've worked on this has been the only static class I've used since this is one of the very few times that I'm in favor of a static class with behavior and state.

I find it much easier to learn about something when it's striped of all the unnecessary fluff. Event busses, domain events, messaging, whatever you want to call it is, in my mind at least, really just easy, ubiquitous, and loosely coupled communication.