LA.NET [EN]

Sep 24

Much has been said about extension methods. Some love it; others see them as evil. Good discussions have been made on when to use them (and when not to use them). Greg Young had a good post on when you might want to use them whenever you control the code of a class (btw, that is good advice that I have been using in my projects with lots of success).

Lately, I’ve been using extension methods for improving an existing API. Let me give you an example. In these last months, I’ve been writing lots and lots of domain code. I’ve also been using NHibernate for persistence and one of the things I need to do is test interation between my repository code and database code – if you’re into the name thingy, I guess that you can call it integration tests.

Many of my tests need to insert or clean a table before testing a specific repository method. I end up using IDbCommands a lot for setting up the data and since it’s the db code is controller by NH transaction, you need to enlist the command in the transaction so that everything works out as expected. What this means, is that I need to write something like this:

using( var session = GetSession() )
{
  using( var tran = session.BeginTransaction() )
  {
     var cmd = DatabaseHelpers.CleanCivilParishTable(); //returns IDbCommand
    tran.Enlist(cmd);
    cmd.ExecuteNonQuery();
   //….more code
  }
}

This is the kind of code that could be improved. What I really want is to have something like this:

DatabaseHelpers.CleanCivilParishTable()
                           .EnlistInNHTransaction(tran)
                           .ExecuteNonQuery();

See, much more readable (I really like fluent interfaces), less key strokes, meaning less probability of having carpal syndrome. To write the previous code snippet, you just need to create a new extension method. Here’s the code for the EnlistNHTransaction method:

public static class IDbCommandExtenders {
   public static IDbCommand EnlistInNHTransaction(this IDbCommand cmd, 
                                                                                  ITransaction tran)
    {
            tran.Enlist(cmd);
            return cmd;
    }
}

Oh,and I’ve also got similar code for adding parameters to anIDbCommand… and some other helpers…

So,who can say that extension methods aren’t cool ?

2 comments so far

  1. Christian Weyer
    4:57 pm - 9-24-2008

    Nice – so post your code :)

  2. luisabreu
    7:11 pm - 9-24-2008

    Christian, would you like to see my helpers? They”re really simple, but I can post them here tomorrow if you want to take a look…

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>