Sunday, January 20, 2008

Template functions

Being a big fan of functional programming languages such as Erlang and Prolog I am very glad to see lambda expressions introduced in C# 3.0 and the VB9. You've been able of writing code in a functional manner since the dawn of C#, but it's been very hard, since version 2.0 it's been easier though with anonymous methods and now with 3.0 and lambda expressions it's truly a walk in the park. One thing I like to do is factoring out common patterns into template functions. A common example of a pattern that is very common is using a database connection and a command for that connection as follows.

using (CustomConnection db = new CustomConnection())
{
    using (IDbCommand command = db.CreateCommand())
    {
        // Database access code here...
    }
}

Now we can factor this out by creating a new delegate type that takes a command and then defining a method that takes such a delegate as an argument.

public delegate void UsingCommandDelegate(IDbCommand command);

public static void UsingCommand(UsingCommandDelegate method)
{
    using (CustomConnection db = new CustomConnection())
    {
        using (IDbCommand command = db.CreateCommand())
        {
            method(command);
        }
    }
}

Now any time we want to make a database call we call this method and pass in the code we want to execute as a lambda expression.

CustomConnection.UsingCommand(command =>
{
    command.Connection.Open();
    command.CommandText = "DELETE FROM [A] WHERE [b] = 'c'";
    command.ExecuteNonQuery();
});

This saves us a couple of lines of code, but the main benefit in this case is that if we want to change any logic regarding how we create connections and commands, let's say we'll change the connection string we can do it in a single location for the whole system. The concept can used in many other cases.

No comments:

Post a Comment