Pages

Thursday, October 24, 2013

Lights, Camera, Action Delegates!

I recently worked on a project that a number of other developers collaborated on. All of the contributors to the project are very smart people, and I was impressed by much of the work that they had done. But one thing caught my eye, and I want to write a post about it since there are folks out there that are not familiar with this technique.

The Func and Action delegates were introduced in .Net 3.5 and they have a variety of uses. One of the best uses that I have found for them is to separate procedural code from actual business logic. Specifically, I like to create methods that accept an action delegate to control database, Entity Framework, or Linq to Sql contexts, and WCF service operations.

In the project I was working on I repeatedly found classes in the data layer with code like this (in this example a connection object has already been created and passed into the class) :

IDbCommand dbCommand = connection.CreateCommand();
dbCommand.CommandText = "Command_Text";

try
{
    if (dbCommand.Connection.State == ConnectionState.Closed)
        dbCommand.Connection.Open();

    dbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
    Log.DefaultLog.WriteVerbose(ex.Message + Environment.NewLine + ex.StackTrace);
    throw ex;
}
finally
{
    if (dbCommand != null && dbCommand.Connection != null && dbCommand.Connection.State == ConnectionState.Open)
        dbCommand.Connection.Close();
}