Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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 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.

Wednesday, December 28, 2011

From collaborator hell to dependency-free bliss

Let's say you're a developer on a C# app and just got a batch of new requirements. Let's also say that it has a fairly simple requirement: when a user closes his or her account, the account status should be set to closed. You, as a good Test Driven Developer, write your unit test, watch it fail, then add the following code to the Account class and watch your test pass:

public void Close() {
  this.Status = AccountStatus.Closed;
}

Easy-peasy.

Many weeks later you come across a requirement that says when a user closes his or her account, the account owner's IsSpecial flag should be set. To make your latest unit test pass, you do the simplest thing that could possibly work.

public void Close() {
  this.Status = Status.Closed;
  this.Owner.IsSpecial = true;
}

Your test went from Red to Green and now it's time to Refactor. Having your Account mutate some value on another object breaks encapsulation so you Control+R & E to Extract Method then Control+R & M to Move your method to the Owner class and give it a clear name.

public void Close() {
  this.Status = Status.Closed;
  this.Owner.ClosedAccount(this);
}

That's a little better. In stead of just setting some property you're now telling the other object that something happened. It's free to handle that how it wants and the Account needn't know about it - a textbook case of encapsulation and The Hollywood Principle.

You've worked in this domain long enough to know that all kinds of things are going to happen when an account is closed. Maybe the other things should be moved to a different method? Not entirely YAGNI, but modifying the account and telling others about it are two different things so you could make the argument that they should be two separate methods.

public void Close() {
  this.Status = Status.Closed;
  this.OnClosed();
}

private void OnClosed(){
  this.Owner.ClosedAccount(this);
}

It's a judgment call but this does clearly separate things. There's one method where the account modifies itself and another where all the other objects get to react to the account being updated. You know that if you have requirements that start with when an account is closed, then the code that deals with the account should go in the Close method and code that deals with other classes goes in the OnClosed method. But wait a second - doesn't this sound familiar? There's even something built into the C# language for just this scenario: events and delegates.

public delegate void ClosedEventHandler(object sender, AccountClosedEventArgs e);

public class Account {
  public event ClosedEventHandler Closed;

  public void Close() {
    this.Status = Status.Closed;

    if (this.Closed != null)
      this.Closed(this, new AccountClosedEventArgs(this));
  }
}

Now the owner can register a callback with the account's Closed event and the account can just tell whoever's listening when it has closed. The Account class no longer needs to reference the Owner class and we can rejoice.

But something about this still doesn't quite seem right. Now instead of the Account telling the Owner, the Owner has to listen to the Account. You still have one class directly referencing and depending on another - you just switched the dependency direction. A day or two later you remember you once read something about Messaging and Domain Events so you look it up and get that started.

public void Close() {
  this.Status = Status.Closed;
  EventBus.Publish(new AccountClosed(this));
}


/* ... elsewhere ... */
public class AccountClosed{
  public Account Account { get; set; }

  public AccountClosed(Account account){
    this.account = account;
  }
}


/* ... elsewhere ... */
class AccountEventsHandler {

  private IRepository repository;

  public AccountEventsHandler(IRepository repository){
    this.repository = repository;
  }

  public void Handle(AccountClosed e){
    this.repository.GetOwner(e.Account).IsSpecial = true;
  }
}


/* ... elsewhere ... */
public void WireEverythingTogether(IRepository repository){
  var accountHandler = new AccountEventsHandler(repository);
  EventBus.Subscribe<AccountClosed>(accountHandler.Handle);
}

Much nicer. Not only is the dependency completely removed from the Account and Owner classes, but each class no longer exposes methods that are just used for reacting to each other. The Account only modifies itself and creates events and the Owner only modifies itself and creates events. Now you have the Account depend on the EventBus and somewhere else you subscribe other classes to the appropriate events. You have a simple AccountEventsHandler that deals with coordinating other objects when the account changes so the domain objects themselves don't need to. It can be little bit more work, but it does reduce coupling and allow much cleaner domain objects. But the Account is still referencing the EventBus directly. You could use a service locator:

public void Close() {
  this.Status = Status.Closed;
  Services.Get<IEventBus>().Publish(new AccountClosed(this));
}

But the service locator can cause problems - like if an IEventBus wasn't registered - and is considered an anti-pattern by some people. You could use constructor injection to pass in the dependency instead.

public Account(IEventBus bus){
  this.eventBus = bus;
}

public void Close() {
  this.Status = Status.Closed;
  this.eventBus.Publish(new AccountClosed(this));
}

That's clean and a good use of the Dependency Inversion Principle, but maybe overkill since the EventBus is so simple and ubiquitous. Maybe hard coding a such a simple dependency is ok. In my limited experience this is an acceptable time for bending the rules and relying on a statefull static class. You will probably never hear me say that again since I hate working with static classes and singletons that have state or complex behavior. On the other hand, constructor injection is a great first step to using a Dependency Injection Container to wire up the EventBus and other dependencies.

Maybe months from now you can switch to actual full-scale event sourcing and CQRS. With command handlers, the Domain Objects create events and store them locally. Then the command handler would fetch all the events from the domain objects and pass them to the event bus; your domain objects don't even need to know about the event bus anymore since the command handler deals with that.



This series of slightly different ways of dealing with different objects involved in the same action is something that I've had a lot of problems with. It's all the same basic result but the important difference is in how to deal with coordinating different objects when something happens. These different designs have very different benefits and costs. The earlier examples are easy for anyone to do, easy to see exactly what happens when debugging or looking at the code, and you know exactly where to make the change: right in the method itself. The downside is that it becomes collaborator hell and all your classes quickly become so bloated that most of the class's code is actually about other classes. The classes become so interdependent that you can't change one thing without having to change everything else. Having lots of dependencies like this can also make build times suffer too. The latter examples only rely on the Event Bus, Service Locator, or Inversion Of Control Container so they are as non-dependent as possible but I can't really tell what's going to happen when the program runs. If everything is wired together with configuration in xml files or sql tables then it can also become exceedingly tedious and error prone to change. This kind of configuration becomes especially difficult if the developer's environment, qa environments, and production environments can all be configured differently. Not everyone will be familiar with or even like the event-based designs either. The whole thing is made even more confusing if different sections of the project have different ways of doing things and people mostly just do whatever they copied and pasted from - not that I've ever done that of course....

Wednesday, February 2, 2011

Interfaces as object contexts

Here's a possibly useful idea I came up with a few weeks ago. I've come across situations where an object needs different behavior depending on the context or how it's used. Usually the state or strategy design pattern (or a mess of if statements) can handle this, but so can explicit interfaces in C#.

First make an interface for each set of behavior you want.

interface IContextA
{
  string Property { get; }
  int Method(int data);
}

interface IContextB
{
  string Property { get; }
  int Method(int data);
}

Then create the different contexts or scenarios using the interface with the behavior you want.

static void DoStuffInContextA(IContextA example)
{
  Console.WriteLine(example.Property);
  Console.WriteLine(example.Method(8));
}

static void DoStuffInContextB(IContextB example)
{
  Console.WriteLine(example.Property);
  Console.WriteLine(example.Method(8));
}

Then create a class that implements the different behavior.

class MultiContextObject : IContextA, IContextB
{
  string IContextA.Property
  {
    get { return "called in context a"; }
  }

  int IContextA.Method(int data)
  {
    return data + 1;
  }

  string IContextB.Property
  {
    get { return "called in context b"; }
  }

  int IContextB.Method(int data)
  {
    return data - 1;
  }
}

And now you can use interfaces to select which set of behavior you want your object to use.

static void ExplicitInterfaceAsContextTest()
{
  MultiContextObject example = new MultiContextObject();
  DoStuffInContextA(example);
  DoStuffInContextB(example);
}

I think this is neat. It won't replace state and strategy patterns, but there's probably cases where those aren't possible or where this would work better.

Friday, January 14, 2011

Enum subsets in C#

After a few years of working with Haskell I've become nearly obsessed with expressing constraints in the type system. Although the C# type system isn't as expressive as Haskell's, preconditions, postconditions, ranges, complexity, and other things can be expressed. If the type is expressive enough then you don't even have to do any validation or checking when working with it because the compiler already guaranteed that the data is valid. One of the problems with C# enums is that they aren't real objects so they can't subclass; they're just pretty wrappers around primitives like ints or bytes. This means that if you only allow certain values of an enum then you have to manually check at runtime:

public void DeclareDayIsSpecial(DayOfWeek day)
{
  if (day == DayOfWeek.Sunday || day == DayOfWeek.Saturday)
    throw new ArgumentException("When declaring that a day is special, the day must be a weekday.", "day");
 
  Console.WriteLine("{0} is special.", day);
}

Even though you can't define an enum as a subclass of another and allow only that subclass, you can define an enum as subset of another.

public enum Weekday
{
   Monday = DayOfWeek.Monday,
   Tuesday = DayOfWeek.Tuesday,
   Wednesday = DayOfWeek.Wednesday,
   Thursday = DayOfWeek.Thursday,
   Friday = DayOfWeek.Friday,
}

Once you have this you can constrain your methods to just the valid subset of values.

public void DeclareDayIsSpecial(Weekday weekday)
{
  Console.WriteLine("{0} is special.", weekday);
}

The compiler won't allow you to use an invalid value so you have compile time documentation and feedback and can remove the runtime checks. This can be useful if you use enums in a scenario where only some values are valid. And since enums are wrappers around primitive types, you can safely cast from the subset (Weekday) to the superset (DayOfWeek).