Aspect-Oriented / Mixin Design Pattern in C#

Update: This works very well with Ninject. It’s very easy to implement, and virtually automatic; see this post I wrote for more details.

As someone with about a year’s worth of experience in Ruby, one of the ideas that fascinated me has been the concept of mixins — creating small, indepdendent units of code that can be cobbled together to instantly add existing, time-tested, robust solutions to existing classes.

While there are several solutions for this in C# 4.0 (thanks to the DLR), I believe I have a solution (via a design pattern) that solves the issue of “tell us at compile time which aspects you support.” But I’m getting ahead of myself. First, the basics.

What are mixins? Mixins can be thought of as multiple inheritance; or they can be thought of as “mixing in” a small unit of existing functionality (methods and properties) into an existing class.

Head First Design Patterns mentions a “duck” application where ducks have three possible behaviours: quacking, flying, and swimming. Every duck is different, so we “layer” this behaviour on via the strategy design pattern and delegation.

This means that your Duck class has a Flying object, and that object either prints “I’m flying!” or “I can’t fly,” depending on the duck. (Wooden ducks and rubber ducks don’t fly.)

A “mixin” or aspect type design would mean separating out the behaviours of flying, swimming, and quacking into aspect classes (you can think of these as regular classes that just encapsulate a small amount of functionality), and combining these with the actual duck class to create the final class.

This means we would be able to write code like Duck.Fly(), which would natively have the same code implemented in the FlyingAspect class, and would print out something like “I’m flying at ” + this._flyingSpeed + “km/h!”, and the respective variables (eg. _flyingSpeed) would be in the aspect class, not the Duck class.

If that confused you, please check out the Head First Design Patterns book on Google Books!

In any case, now that .NET 4.0 has the DLR, we can easily solve this problem by using a dynamic object, and using some sort of post-compilation process to add metadata from the (Flying) aspect into the (Duck) class. You can even write your own code generator to do this; you can write someDuck.Fly(); and it would compile and run and everything would work.

There are plenty of existing aspect-oriented frameworks like this; Microsoft even recommends something similar — they use the same idea of “weaving” the aspects into the final code to create the composite class.

But they all have the same flaw: you cannot determine at compile-time if the method will work or not. Maybe that’s not a big deal for you — if not, you can stop reading here. But if so, I’ve devised a somewhat flexible solution to deal with this.

Let’s back-track a bit. What are the core, fundamental ideas of aspects that we want to support?

  1. Aspects provide encapsulated properties and methods to objects that use them. The code is “DRY” — it’s only in one place (in the aspect code).
  2. A class can implement any number of aspects.
  3. We can determine at compile time which objects use which aspects.
    • Let’s provide a solution to each of these issues one by one.

      First, encapsulating the code: there’s a wonderful design pattern called “inheritence by composition” (also known as inversion of control) which comes to the rescue here. Let’s take the duck example — we can create a class called FlyingAspect, which exposes methods like Fly and properties like FlyingSpeed. We can then instead of making duck extend FlyingAspect, Duck can have a flying aspect instance variable and redirect all flying-related calls to it.

      This would look like:

      class Duck {
      private FlyingAspect _flying = new FlyingAspect();
      public void Fly() { this._flying.Fly(); }
      public int FlyingSpeed { get { return this._flying.FlyingSpeed;}}

      This is also known as “delegation,” since we delegate the required behaviours to the right object. This way, we only implement flying logic once, inside the FlyingAspect class.

      Pretty good — this also covers issue #2, that a class can implement any number of aspects; simply add more instance objects and delegate the calls accordingly.

      But what about the final issue — determining aspect-support at runtime? This is a hard problem to solve; we cannot guarantee at compile-time which class implements which aspect. We could use reflection to peek into the class, extract all member variables that extend the Aspect class, and assume those are aspects; but again, that’s at runtime. What about at compile-time?

      There’s another problem here — there’s no guarantee that we’re implementing the (whole) aspect correctly. We might forget to implement one method that FlyingAspect requires; or worse, FlyingAspect will add and change methods, and we’ll forget to update our Duck class accordingly.

      Both of these issues can be addressed with a simple solution: interfaces. We can use an interface to represent an aspect, and require the class and the aspect’s concrete implementation to verify at compile-time.

      Our updated code would look like this:

      interface IFlyingAspect {
      void Fly();
      int FlyingSpeed { get; }

      class FlyingAspect : IFlyingAspect {
      int _flyingSpeed = 100;
      void Fly() { ... }
      int FlyingSpeed { get { return _flyingSpeed; }}

      class Duck : IFlyingAspect {
      private FlyingAspect _flying = new FlyingAspect();

      public void Fly() { _flying.Fly(); }
      public int FlyingSpeed { get { return _flying.FlyingSpeed; }}

      As you can see, both classes implement the interface — this allows us to guarantee at compile-time that the aspect is implemented (along with its corresponding properties and methods), and still allows us to have the actual flying code isolated in one place.

      What are your thoughts on this? It’s a pretty simple design pattern; and it addresses the implementation of aspects beautifully and simply through delegation and interfaces.

6 Responses to Aspect-Oriented / Mixin Design Pattern in C#

  1. StefanPapp says:

    Very good article.

    You might be interested that now there is an open source library available on codeplex that brings mixins to .NET

    For more information checkout

    Thank you!

  2. kobi says:

    nice way to solve this problem!
    there is another way to implement mixins, and that is with interfaces and an extension method that dispatches on this interface type.
    Basically same as interface, only the implementation won’t have to be done on every class that inherits the interface. Since it will get this functionality from the extension method
    interface IFlyingAspect {
    void Fly();
    int FlyingSpeed { get; }
    static class FlyingExtensions
    public void Fly (this IFlyingAspect bird)

    then class Duck : IFlyingAspect
    automatically gets the functionality.
    the only issue less than ideal is that the interface and extension method are not encapsulated together.

  3. Ashiq Alibhai, PMP says:

    @kobi I never thought of using extension methods for it. I’ll try it out, and update my design if it works. That solves the annoyance of having to implement it on each class — but it prevents you from overriding mixed-in functionality.

  4. Ranjan says:

    You should probably inject the dependency of IFlyingAspect in Duck class. So that you wont be creating a concert instance of FlyingAspect within Duck and you have the flexibility of passing any object which implements IFlyingAspect interface

    I don’t think extension method is a good idea for creating mixins

  5. Ashiq Alibhai, PMP says:

    @Ranjan I think you have a good point. Having defined interfaces, maybe injection is the next logical step.

  6. Techno Tom says:

    Awesome to the max. You just invented the Proxy Pattern…again.

Leave a Reply

Your email address will not be published. Required fields are marked *