Many lines of code in C# and other imperative languages are seemingly wasted by dealing with overhead such as exception handling and the like. How many times have you written the following type of code?

string[] fileNames;

try
{
    fileNames = Directory.GetFiles(…);
}

catch (Exception)
{
    // There was an error, like the directory isn’t there.
    // This isn’t an error for us, so just use a 0-length array
    // to simplify our later code
    fileNames = new string[0];
}

foreach (string fileName in fileNames)
{
    … do some processing on this file …
}

The basic pattern is, "try to obtain a value by calling this function, but if there’s an error then use a default value." It’s a lot of code, and it gets tiring and unreadable or unmanageable after awhile. This pattern, which is called the hole in the middle pattern, crops up all the time in imperative programming. The structure of this block of code is consistent, but there’s that little part in the middle that’s always changing. Most of the time we just trudge through the code because we want to get our stuff done, clock out, then go home and drink beer.

C# 3.0 adds a nice feature called lambda expressions, which is mostly syntactic sugar for anonymous delegates. Using them along with continuation-passing style we can write some helper functions that make this type of code much easier to deal with, and more expressive and succinct. In Paint.NET I’m adding a static class called "Do" that will help out with my code:

(Please note that Paint.NET’s "Function" delegate has the type parameters reversed from .NET 3.5′s "Func" delegate. "Func" delcares them in the traditional functional or mathematical ordering, where "F x -> y" is equivalent to "y F(x)". So, my code uses the "y-x" order. I added "Function" before .NET 3.5 added "Func", so let’s not get on my case about the ordering … :) )

public static class Do
{
    public static T TryCatch<T>(Function<T> actionFunction, Function<T, Exception> catchClause)
    {
        T returnVal;

        try
        {
            returnVal = actionFunction();
        }

        catch (Exception ex)
        {
            returnVal = catchClause(ex);
        }

        return returnVal;
    }
}

(Quick digression: You’ll note that I do not assign to returnVal at the beginning of the function. This is a pattern I use quite often, because the C# compiler always does analysis to ensure a variable is assigned to before being used. This lets me make sure I always assign a meaningful value, and don’t miss the assignment in any of my branches or clauses. If I were to immediately assign "null", for instance, but then I forgot to assign a meaningful value to it in some if/else branch, then that error would go undetected.)

Once we have this utility function, the first code snippet simplifies to the following:

foreach (string fileName in Do.TryCatch(() => Directory.GetFiles(…), ex => new string[0]))
{
    … do some processing on this file …
}

Voila :) I’m actually using this code in the setup wizard, as it needs to get a list of files in a directory and then delete them. If the directory doesn’t exist then there’s really nothing to do, but it also isn’t an error, and having the try/catch around the call wreaks havoc on the simplicity of the code. This lets me express that much more succinctly.

There are other patterns you can use, such as passing lambdas for the finally clause, or passing lambdas for various exception types, or even returning the exception for more imperative style processing.

About these ads