Friday, 4 July 2008

Full disclosure: Bought off with a ReSharper licence

In the interest of full disclosure, I recently got sent a free ReSharper 4.0 Personal Licence from JetBrains. I really don't know why. The explanation in the email I received was very generic: "for donating so much of your time... whether in the form of plugin development, quality verifying, promoting or educating about ReSharper".

I emailed them back and asked why I got included in the list for a free licence, but haven't received a response. All I've done for ReSharper/JetBrains is left them a comment or two, downloaded the R# 4.0 nightlies and maybe even tried to submit one of those automated bug submission thingoes (which I think failed due to the proxy at my work). I have blogged a couple of times on ReSharper, although never anything high-traffic. So I'm at a loss to explain why.

I haven't used the licence yet (was hoping to find out why I got it first), but I guess you can probably disregard anything positive I've ever said about R# now I'm owned by them after being sent free swag. In fact, just assume from now on that I have absolutely no integrity whatsoever. Luckily astute readers are already way ahead of me on that... :)

And no, I can't give it to you instead because the licence is non-transferable :P

Wednesday, 2 July 2008

Write out the fields of a JavaScript object

I've found myself writing this bit of code a few times now, so thought I'd dump it here for future copy-and-paste.

function writeObj(obj, message) {
  if (!message) { message = obj; }
  var details = "*****************" + "\n" + message + "\n";
  var fieldContents;
  for (var field in obj) {
    fieldContents = obj[field];
    if (typeof(fieldContents) == "function") {
      fieldContents = "(function)";
    }
    details += "  " + field + ": " + fieldContents + "\n";
  }
  console.log(details);
}

This just dumps all the object's fields into the debugging console provided by the Firebug extension for Firefox (the console.log(...) call). If you don't have Firebug, you can easily create a custom console object to provide an alternative log method. For example, put this snippet at the top of the script to use window.alert(...) when console is undefined:

if (!console) {
  var console = {log: function(details) { window.alert(details); }}
}

There are probably better ways of doing this, but I find this handy so I can quickly mash writeObj(myObject) into the console and get a list of all the object's fields. For more fun with simple JavaScript reflection have a look at my earlier post on the subject.

Monday, 23 June 2008

@ prefix for C# names

Who'd have thought I'd learn something over Twitter (during an uncharacteristic period of uptime)? Nothing overly useful mind you, just an interesting bit of trivia. :)

Besides "yuck", what would you think when you saw the following C# code?

class @class {
  public string @someValue;
  public int @int;
}

[Test]
public void TestAtClass() {
  @class myclass = new @class();
  myclass.@int = 10;
  myclass.@someValue = "test";
}

Prior to today I'd have thought that it wouldn't compile, but after seeing a tweet from Brad Wilson that mentioned you could use @ to prefix variable names I thought I'd give it a try, and sure enough the C# compiler is happy. Brad's tweet was about using @ to prefix reserved words so you can get names like @class.

Bit evil perhaps, but all those @'s might make some Rubyists feel a bit more at home in C# ;-)

Saturday, 21 June 2008

Yet another way of raising events from mocks

Update 2008-06-26: This is now in the Rhino Mocks trunk, so it should be available as part of the 3.5 release.

I've been playing around with raising events from mocks for the last couple of nights, and think I've finally come up with an approach that works for me. Finding a nice way of raising these events is particularly tricky for mock object frameworks, as the C# compiler is really picky about how you can use event references. For example, let's look at a very useful interface:

public interface IDoSomething {    
    event EventHandler SomethingDone;
}

Outside of a class that implements IDoSomething, the only time we can reference SomethingDone is when we are adding or removing listeners (x.SomethingDone += someEventHandler; or x.SomethingDone -= someEventHandler;). (C#'s lack of real support for System.Void is partly to blame here, as both these operations are void.)

To raise an event on a mock object, it would be lovely to be able to code something like this:

var mock = mocks.DynamicMock();
mock.Raise(mock.SomethingDone, mock, EventArgs.Empty);

Unfortunately due to the aforementioned constraint, the emphasised part of the code will give a compiler error stating "The event 'IDoSomething.SomethingDone' can only appear on the left hand side of += or -=".

There are a few workarounds for this. Let's start with the standard Rhino Mocks approach. (I'm using Rhino Mocks 3.5 beta and xUnit.net here -- feel free to translate from [Fact] to [Test] if you use NUnit, MBUnit et al.)

[Fact]
public void Raise_event_old_style() {
    var mock = mocks.DynamicMock<IDoSomething>();
    mock.SomethingDone += null;
    IEventRaiser eventRaiser = LastCall.IgnoreArguments().GetEventRaiser();
    mocks.ReplayAll();

    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;
    eventRaiser.Raise(mock, EventArgs.Empty);

    mocks.VerifyAll();  
    Assert.True(wasCalled);
}

Rhino Mocks records the expectation that an event handler is added, then uses LastCall to ignore the argument and gets an IEventRaiser for the last event referenced. That IEventRaiser can be used later on to raise our event. Phil Haack has a helpful post which explains a bit more about this approach.

When I first saw this I must admit it seemed like a lot of noise that obscured what I was really trying to do. This got worse when I started playing around with the new Arrange - Act - Assert syntax and I didn't want to go through the whole replay / verify cycle. So I started looking at the Rhino Mocks implementation of IEventRaiser, the EventRaiser class. This class lets us do this:

[Fact]
public void Raise_event_using_string_for_event_name() {
    var mock = mocks.DynamicMock<IDoSomething>();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;

    var eventRaiser = EventRaiser.Create(mock, "SomethingDone");
    eventRaiser.Raise(mock, EventArgs.Empty);
    
    Assert.True(wasCalled);
}

Here we can specify the relevant event using a string. This works nicely and is easy to read, but causes problems when refactoring and means we don't get intellisense or compiler assistance. Ayende has written about this approach, comparing it with the LastCall.GetEventRaiser() approach we used last time.

I wasn't overjoyed about either of these, and while searching around for other options I found another of Ayende's posts (I think his blog is about 30% of the web... great stuff :)), asking for feedback on a more natural syntax for raising events from mocks. This looked a bit like this:

mock.MyEvent += EventRaiser.Raise(this, EventArgs.Empty);

I quite liked this, but there were a few complaints in the comments about subscribing to and raising the event at the same time. The post was from about 12 months prior to me writing this and, as I'm using a recent Rhino Mocks build and couldn't find it, it looks like nothing came of this. Let's look for a compromise that also fits in nicely with our Arrange - Act - Assert approach. First we'll see what we can get working based on the first, LastCall.GetEventRaiser() approach used:

[Fact]
public void Raise_event_with_new_arrange_act_assert_syntax() {
    //Arrange
    var mock = MockRepository.GenerateMock<IDoSomething>();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;
    
    var eventRaiser = 
        mock
        .Stub(x => x.SomethingDone += null)
        .IgnoreArguments()
        .GetEventRaiser();
    
    //Act
    eventRaiser.Raise(mock, EventArgs.Empty);

    //Assert
    Assert.True(wasCalled);
}

Here we are specifying a fairly useless stub so we can get an IEventRaiser. We are still using ye olde x.SomethingDone += null trick (albeit with a lambda to neaten it up), but we are pretty much stuck with that if we want strong typing on this as discussed at the beginning of this post.

I think this looks a bit more cohesive now we are using the lambda. We have one statement that is fairly obviously getting an IEventRaiser, rather than a null event handler floating around on its own confusing poor people like me :). Beyond aesthetics, this cohesion can let us pull out this functionality and start getting closer to a neater syntax. For now we'll just whack this in a .NET 3.5 extension method, but we could probably find a better home for it (it can go in a standalone class but the final syntax doesn't read quite as well to me).

public static class EventRaiserExtensions {
    private static IEventRaiser GetEventRaiserFromSubscription<TEventSource>(
        this TEventSource mock, Action<TEventSource> eventSubscription) {
        return mock
            .Stub(eventSubscription)
            .IgnoreArguments()
            .GetEventRaiser();
    }
    
    public static void Raise<TEventSource>(this TEventSource mock, Action<TEventSource> eventSubscription, object sender, EventArgs args) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(sender, args);
    }

    public static void Raise<TEventSource>(this TEventSource mock, Action<TEventSource> eventSubscription, params object[] args) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(args);
    }        

    public static void Raise<TEventSource>(this TEventSource mock, Action<TEventSource> eventSubscription) {
        var eventRaiser = GetEventRaiserFromSubscription(mock, eventSubscription);
        eventRaiser.Raise(mock, EventArgs.Empty);
    }    
}

The emphasised bit of code is the stub call we did last time, but this time pulled out into one method. The main bits are the Raise<TEventSource> extension methods, which combine all the steps and give us an easy syntax for calling an event on a mock based on an event subscription delegate. So our example now looks like this:

[Fact]
public void Suggestion_for_raising_events() {
    var mock = MockRepository.GenerateMock<IDoSomething>();
    var wasCalled = false;
    mock.SomethingDone += (sender, e) => wasCalled = true;

    mock.Raise(x => x.SomethingDone += null, mock, EventArgs.Empty);

    Assert.True(wasCalled);
}

The implementation itself might need work, but I reckon that syntax is pretty neat considering the limitations of C#. Of course, you're welcome to think otherwise, so please leave a comment expressing your outrage and/or contempt :).

Disclaimer: I am fairly new to Rhino Mocks (have tended to stick to manual test doubles) and especially to Arrange - Act - Assert (it's only in beta at present), so this might fail pretty hard in other circumstances. Still, I thought I'd post the syntax in case it gave more knowledgable people some good ideas :)

Friday, 20 June 2008

Subversion 1.5.0 released

Just saw that Subversion 1.5.0 has been released. There are quite a few new features, but the main ones of interest to me are:

See the svn 1.5 release notes for a run down of the main changes, or the CHANGES file for a complete list.

Oh yeah, and the usual, major version, working copy and repository format provisos apply... while the API is backwards compatible and svn 1.5 server and tools work with older repo versions, working copies are a different story. Older client tools will not work with svn 1.5 working copies, nor with 1.5 repositories. Your existing working copies will automatically upgrade to the 1.5 format when you access them with the new tools. Read this for more information.

You'll also need to upgrade your repository format to 1.5 to take full advantage of the new features like merge tracking (although you'll get a number of the improvements with older repo formats as well).

Certified binaries will be coming out over the next couple of days at CollabNet (other binary maintainers listed here). The TortoiseSVN crew is pretty much ready to go too.

Thursday, 19 June 2008

DI and cross-cutting concerns

Just came across some great guidance from Casey Charlton on the ALT.NET mailing list. My last post on dependency injection mentioned the benefit of documenting class dependencies via the constructor used for DI. But what about cross cutting concerns like logging? From Casey's mailing list post:

"Constructor properties shouldnt be used for cross cutting concerns like logging ... Put ILogger as a public property on the class, use the nulllogger as the default value, register the logging facility in Windsor, and all will magically happen"

I like this -- unique dependencies in your constructor, others set via property-injection. I'm also pretty keen on the idea of AOP for doing a lot of basic logging, but I haven't had a good look at this in .NET yet. The ALT.NET thread has a bit more of a discussion on logging.

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.