Showing posts with label patterns. Show all posts
Showing posts with label patterns. Show all posts

Thursday, 12 June 2008

Attempting to understand Dependency Injection

Watching Rob Conery and Jeremy Miller work through Dependency Injection for the MVC Storefront project really helped me to piece together a few ideas that had been rattling around in my generally deserted cranium. Dependency injection (DI) is sometimes dismissed as "just" a tool for unit testing and mocking dependencies. But I think DI, and DI containers, offer a bit more to software design than simply providing a way to use mocks for interaction testing. So as usual I'm polluting the blogosphere with my ramblings in an effort to solidify my understanding. Let's work through an example and see what we can find.

Here is how we could write a class to send invoice reminder emails without any thought given to design or testability:

public class InvoiceReminderService {
  public void SendReminders() {
    var emailService = new EmailService();
    var invoiceRepository = new InvoiceRepository();  
    var invoicesDueForReminderEmail = invoiceRepository.GetInvoicesDueForReminders();
    foreach (var invoice in invoicesDueForReminderEmail) {
      var reminderMessage = createReminder(invoice);
      emailService.Send(reminderMessage);
    }
  }
  //...
}

Here we have dependencies on InvoiceRepository, for getting invoices due for reminder emails, and EmailService, for sending out the emails over SMTP. These dependencies could be instantiated at many different places all over our code base. Without worrying about design principles or testability, let's simply pull out these dependencies and rely on constructor injection to instantiate them.

public class InvoiceReminderService {
  private EmailService emailService;
  private InvoiceRepository invoiceRepository;

  public InvoiceReminderService(InvoiceRepository invoiceRepository, EmailService emailService) {
    this.invoiceRepository = invoiceRepository;
    this.emailService = emailService;
  }

  public void SendReminders() {
    var invoicesDueForReminderEmail = invoiceRepository.GetInvoicesDueForReminders();
    foreach (var invoice in invoicesDueForReminderEmail) {
      var reminderMessage = createReminder(invoice);
      emailService.Send(reminderMessage);
    }
  }
  //...
}

Here we've just created a constructor that takes the required dependencies and adds them to private fields. SendReminders() has been updated so that it is no longer responsible for instantiating the dependencies. I can then instantiate an InvoiceReminderService by creating the dependencies and passing them to the constructor, or I can use a DI container (I'm using a pre-release build of StructureMap 2.5 for this post) to automatically create my dependencies for me:

var invoiceReminderService = ObjectFactory.GetInstance<InvoiceReminderService>();

By default our DI container looks at the greediest constructor (the one with the most parameters) to see what dependencies it needs to create. Because InvoiceRepository and EmailService are both concrete classes (i.e. not interfaces or abstract), we don't need to give StructureMap any additional information, it can simply instantiate the required objects and pass them through to the InvoiceReminderService constructor.

So what has this accomplished? Well, SendReminders() is now a lot clearer without the dependencies in the way. And we also have an easy way to tell exactly what the dependencies of the class are (the constructor). We are also skirting dangerously close to having a testable class that could easily be modified to follow the Dependency Inversion Principle (DIP) (by extracting interfaces from our dependencies and relying on those instead of on concrete classes) and the Open/Closed Principle (OCP) (by allowing us to change the behaviour of our class by providing different implementations for the dependencies).

But the main, obvious thing this has accomplished is that our class is no longer responsible for instantiating its dependencies. I guess you could almost link this back to the Single Responsibility Principle (SRP) -- we are limiting this class' responsibilities and given it one less reason to change. Why is this good? Well, let's imagine our EmailService class is used by a number of classes throughout our application. We want to change our EmailService so that it no longer sends emails directly via SMTP. Now it simply queues up the email in a database, and another process is responsible for firing off emails from the queue. To create an EmailService without a DI container I now need to do this to every class that builds an EmailService:

emailService = new EmailService(new EmailRepository());

Or we can just let my DI container handle it for me, and keep our original ObjectFactory call unchanged. This reduces the friction experienced whenever we need to factor out a new class to provide new functionality or to avoid an SRP violation.

//No change need here, even though the EmailService constructor has changed...
var invoiceReminderService = ObjectFactory.GetInstance<InvoiceReminderService>();

(Yes, this is slightly circular logic as I am assuming we using DI for the new EmailRepository class too, but the logic is equally valid if we want to change the constructor to include a connection string or some other parameter. The point is that we can vary the instantiation without affect dependent classes.)

Now I'm not suggesting for a moment that you want to globally replace new with a DI container, but for me the realisation that DI containers were all about abstracting the responsibility of dependency creation, rather than simply providing a testing seam, was a bit of an A-HA! moment. Of course, I am a bit slower than your average developer, so sometimes the things like this take me a while :-)

From abstracting dependency creation to SOLID designs

Now there are still a number of SOLID design principles the code above is violating. This doesn't mean we need to instantly refactor to be compliant (you're never going to be, they are general guidelines that can be somewhat contradictory when taken to the n'th degree), but it is something we can look at.

First up is the DIP. We are depending on concrete types rather than abstractions. This also limits our options of altering the behaviour of the class via its dependencies to subclassing those dependencies, which is a minor strike against the OCP. This is easily fixed by extracting interfaces from the dependencies:

public class InvoiceReminderService {
  private IEmailService emailService;
  private IInvoiceRepository invoiceRepository;

  public InvoiceReminderService(IInvoiceRepository invoiceRepository, IEmailService emailService) {
    this.invoiceRepository = invoiceRepository;
    this.emailService = emailService;
  }
  //...
}

StructureMap will auto-wireup these dependencies, but if we are using our EmailService implementation that depends on an extracted IEmailRepository interface, then we'll need to tell StructureMap's configuration about it, either at compile time in code or using a configuration file:

public static class Bootstrapper {
  public static void ConfigureIoC() {            
    StructureMapConfiguration.AddRegistry(new DiSampleRegistry());
  }  
}
public class DiSampleRegistry : Registry {
  protected override void configure() {
    ForRequestedType<IEmailRepository>()
      .TheDefaultIsConcreteType<EmailRepository>();                
  }
}

We are now looking at a more traditional DI design. Our InvoiceReminderService is now completely independent of the specific implementations of its dependencies. All the code in the class is cohesive -- working at one responsibility with minimal background noise. This project doesn't even need a reference to the DLL containing the dependency implementations. This means we are fine changing implementations (although not interface contracts!) and we know our InvoiceReminderService is safe. If you were given this class to reuse, or simply to maintain, you wouldn't have to go pulling in a whole bunch of concrete dependencies. As a result and as a nice bonus, we have some good seams for running automated tests. We can easily stub or mock these dependencies and isolate the behaviour under test.

Aside: DI containers are an obvious way to get plugin and provider-style implementations, by loading specific implementations of an interface at runtime. I'm focusing on more general design effects here -- if you're looking for a plugin/component/provider model you'll obviously be designing more explicitly for loose coupling and will choose your approach based on that.

Not all beer and Skittles?

That's the DI theory, as far as I can tell. But as always there is no silver bullet. It is now tougher for us to navigate from the InvoiceReminderService to the current implementations of its dependencies (as we've abstracted them away). We are also looking at a potential interface explosion. Why extract an interface for virtually every class you write? That's two units of code for every responsibility. And we now have a DI container to learn and troubleshoot when debugging. If we're happy with tight coupling between this class and its dependencies, then why go to these lengths? If you want to run unit tests why not just use TypeMock to break into tightly coupled dependencies? Or at the very least provide default implementations in the class' default constructor (a.k.a. the poor man's dependency injection, see Nikola's post for an interesting variation on this approach):

public class InvoiceReminderService {
  private IEmailService emailService;
  private IInvoiceRepository invoiceRepository;

  public InvoiceReminderService() {
    this.invoiceRepository = new InvoiceRepository();
    this.emailService = new EmailService();
  }

  public InvoiceReminderService(IInvoiceRepository invoiceRepository, IEmailService emailService) {
    this.invoiceRepository = invoiceRepository;
    this.emailService = emailService;
  }  
  //...
}

And how much of all this is just working around limitations of statically typed languages? To me these are all quite reasonable questions (some of these raised by Kevin Berridge in some nice posts here and here, as well as a couple of posts from Jacob Proffitt starting here).

As always the key seems to lie in achieving a balance. The benefits of a loosely coupled design always need to be traded off with any additional complexity of that design. After watching the MVC Storefont DI screencast and having a play around with StructureMap I can see a lot of very obvious benefits to DI containers, but at the same time it's not something to dive into without having an vague idea of the theory and problems it aims to solve (which is why I've spent so much time reading about DI containers, but generally sticking to poor man's DI until I had a pressing reason to move to a container). After all, we don't go around blindly applying the GOF patterns to every situation under the sun... right? :-)

Some interesting DI reads

As opposed to this post, here are a few interesting takes on DI.

Thursday, 1 November 2007

Double dispatch

Jeremy Miller recently had a post that mentioned "double dispatch", and I had to delve down into the dusty recesses of my at-best-mediocre brain to come up with a definition. Chances are everyone has come across double dispatch in one form or another, and understands it implicitly. However I find it harder to articulate the definition explicitly.

My (admittedly limited) understanding of double dispatch is that it chooses a method to evaluate based on the runtime types of two objects. Also, C# does not support double dispatch, but you can emulate it a number of ways by doing reflection tricks or by using a Visitor-pattern style approach. To illustrate the limitations in C#, I'll borrow the example from Wikipedia and collide some asteroids with spaceships.

[TestFixture]
public class DispatchBehaviour {
  public class SpaceShip { }
  public class GiantSpaceShip : SpaceShip { }
  public class Asteroid {
    public virtual String CollideWith(SpaceShip ship) {
      return "Asteroid hit a SpaceShip";
    }
    public virtual String CollideWith(GiantSpaceShip ship) {
      return "Asteroid hit a GiantSpaceShip";
    }
  }
  public class ExplodingAsteroid : Asteroid {
    public override string CollideWith(SpaceShip ship) {
      return "ExplodingAsteroid hit a SpaceShip";
    }
    public override string CollideWith(GiantSpaceShip ship) {
      return "ExplodingAsteroid hit a GiantSpaceShip";
    }
  }
  [Test]
  public void TestFailsWhenTryingDoubleDispatch() {
    SpaceShip ship = new SpaceShip();
    SpaceShip giantShip = new GiantSpaceShip();
    Asteroid asteroid = new Asteroid();
    Asteroid explodingAsteroid = new ExplodingAsteroid();
    Assert.That(asteroid.CollideWith(ship), Is.EqualTo("Asteroid hit a SpaceShip"));
    Assert.That(explodingAsteroid.CollideWith(ship), Is.EqualTo("ExplodingAsteroid hit a SpaceShip"));
    //This assertion fails:
    Assert.That(explodingAsteroid.CollideWith(giantShip), Is.EqualTo("ExplodingAsteroid hit a GiantSpaceShip"));
 
  }
}

The explodingAsteroid reference looks up the correct virtual function in the ExplodingAsteroid class despite it being referenced via the Asteroid type, thanks to polymorphism and virtual functions. But because C# uses single dispatch, the above test fails because based on the compile-time lookup of the giantShip reference (which is a SpaceShip reference at compile-time). If it where doing that lookup at run-time we'd have a different story.

One way of dealing with this is to switch on the type within the CollideWith methods.

public class ExplodingAsteroid : Asteroid {
  public override string CollideWith(SpaceShip ship) {
    if (ship is GiantSpaceShip) {
      return "ExplodingAsteroid hit a GiantSpaceShip";
    } else {
      return "ExplodingAsteroid hit a SpaceShip";
    }
  }
}
//...similar implementation for Asteroid.CollideWith(...)

This works, but if you end up with lots of different SpaceShip types then you are in for a hard time. If your group of asteroids is fairly static, you can use a Visitor-approach to accommodate lots of different spaceships. First we'll define an IAsteroid interface to represent the fairly stable group of asteroids, and an IAsteroidTarget as a Visitor, to represent anything that can collide with our stable group of asteroids:

//Element that accepts a visit, in Visitor pattern parlance
public interface IAsteroid {
  string CollideWith(IAsteroidTarget target);
}
//Visitor, in Visitor pattern parlance
public interface IAsteroidTarget {
  String CollideWith(Asteroid asteroid);
  String CollideWith(ExplodingAsteroid asteroid);
}

As our spaceships can "visit" the asteroid types, let's implement those next:

public class SpaceShip : IAsteroidTarget {
  public string CollideWith(Asteroid asteroid) {
    return "Asteroid hit a SpaceShip";
  }
  public string CollideWith(ExplodingAsteroid asteroid) {
    return "ExplodingAsteroid hit a SpaceShip";
  }
}
public class GiantSpaceShip : IAsteroidTarget {
  public string CollideWith(Asteroid asteroid) {
    return "Asteroid hit a GiantSpaceShip";
  }
  public string CollideWith(ExplodingAsteroid asteroid) {
    return "ExplodingAsteroid hit a GiantSpaceShip";
  }
}

Now comes the double-dispatchy emulation part. Let's make our asteroids accept visits from our IAsteroidTarget objects.

public class Asteroid : IAsteroid {
  public string CollideWith(IAsteroidTarget target) {
    return target.CollideWith(this); // <-- The double dispatchy part
  }
}
//Same implementation for ExplodingAsteroid : IAsteroid ...

The emphasised part of the code above delegates the way each target will be hit to the target itself. A slightly modified version of our original test will now pass:

[Test]
public void TestDoubleDispatchWorkAround2() {
  IAsteroidTarget ship = new SpaceShip();
  IAsteroidTarget giantShip = new GiantSpaceShip();
  IAsteroid asteroid = new Asteroid();
  IAsteroid explodingAsteroid = new ExplodingAsteroid();
  Assert.That(asteroid.CollideWith(ship), Is.EqualTo("Asteroid hit a SpaceShip"));
  Assert.That(explodingAsteroid.CollideWith(ship), Is.EqualTo("ExplodingAsteroid hit a SpaceShip"));
  Assert.That(explodingAsteroid.CollideWith(giantShip), Is.EqualTo("ExplodingAsteroid hit a GiantSpaceShip"));
}

Obviously there are disadvantages to this pattern. If you need to add more asteroid types things are going to be painful. (There are also much better ways of implementing this particular example of returning strings, but that is just due to its contrived nature. For a realistic example see Jeremy's post.) On the other hand, the process of adding targets is now trivial, even non-spaceship ones:

public class Earth : IAsteroidTarget {
  public string CollideWith(Asteroid asteroid) {
    return "Asteroid hit Earth";
  }
  public string CollideWith(ExplodingAsteroid asteroid) {
    return "ExplodingAsteroid hit Earth, causing the extinction of the dinosaurs";
  }
}

As an aside, this single dispatching behaviour of C# explains the cause of the generic overloading behaviour I mentioned before.

Finally, Derrick Coetzee has a good explanation of technical aspects of dispatching in C# with regards to the Visitor pattern.

Wednesday, 20 June 2007

MVP and SharePoint Web Parts

Bil Simser writes about Model-View-Presenter Pattern with SharePoint Web Parts. It is a simple, well explained example, and tying it back to Web Part development instead of the standard ASPX development is nice.

Thursday, 14 June 2007

Domain Centric Validation with the Notification Pattern

 Jeremy D. Miller as churned out another fantastic post on Domain Centric Validation with the Notification Pattern as part of his "Build your own CAB" series.

This describes putting validation logic in the model code using custom attributes (similar to the Validation Application Block) and the notification pattern to collect the results and pass to other layers. Reading through the example is great way to learn and reinforce concepts like separating concerns and writing testable code.

Monday, 16 April 2007

Considering a View's Get/Set Roles with MVP

Billy McCafferty has a nice post titled Considering a View's Get/Set Roles with MVP. Billy looks at various implementations for setting and getting data to and from a view, including getter/setters with entities and DTOs, and also using an Update method on the view.

Design Patterns in ASP.NET 2.0

Alex Homer has written a 3-part article series on Design Patterns in ASP.NET 2.0.

I don't agree with everything in the article. For example, I (et al.) don't consider the code-behind model a valid implementation of the Model View Presenter pattern. Just because some presenter and view code is physically separated into different files does not change the fact that logically they are the same class and generally tightly coupled to each other.

Another point I disagree on is Alex's implementation of the Singleton pattern, which does not look thread safe to me, especially when you can get the safety for free in .NET using a static readonly property and a static constructor.

What I did find helpful in the article is the plain language explanation of the patterns concerned and the areas where they can be applied to .NET.

Tuesday, 3 April 2007

The Humble Dialog approach to MVC

Michael Feathers' famous paper titled "The Humble Dialog Box" has a nice, simple summary of the steps require to develop a controller class for the model-view-controller pattern:

  1. Create a class for the smart object, and an interface class for the view. Pass the view to the smart object
  2. Develop commands against the smart object, test first. Write your tests against a mock view.
  3. Create your dialog class and implement the view interface on it. Gestures on the dialog should delegate to commands on the smart object. Calls from the smart object to the dialog should resolve to simple setter methods.

All the articles on Michael's site are worth a read.

Friday, 9 March 2007

More MVP with TDD goodness

Nice article on test driving an .NET, MVP-based UI - Becoming Agile: Model View Presenter - is testing the presenter enough?

Wednesday, 21 February 2007

Walkthrough of writing a Model View Presenter in ASP.NET

Wednesday, 10 January 2007

More Patterns: Enterprise Integration Patterns website

Another good patterns reference is the website for the Enterprise Integration Patterns book by Gregor Hohpe and Bobby Woolf.

Thursday, 4 January 2007

MartinFowler.com - articles and pattern catalogues

Martin Fowler, author of "Patterns of Enterprise Application Architecture" and others, maintains a web site of programming articles, references and patterns.

Tuesday, 19 December 2006

Model View Presenter pattern for ASP.NET

Here are some links to information about using Model-View-Presenter (MVP) for ASP.NET development.

First some general information from Martin Fowler: the rationale behind GUI architectures such as MVP, and his subsequent splitting of MVP into two patterns (Supervising Controller and Passive View).

Next, a code sample provided by Scott Cate, and summarised by David Hayden. Jeremy D. Miller also has a good post on TDD, MVP and ASP.NET, and a later post providing some additional comments. Finally, a CodeProject article by Bill McCafferty on MVP within ASP.NET 2.0.

UPDATE: Found a nice link summarising and describing the differences between Model-View-Controller (MVC) and MVP patterns.