Adapting Method Signatures…Functional Style

26. March 2010 00:09

Over the last year or so, I’ve become increasingly interested in functional programming.  There is just something elegant and sexy about the ways in which it can be applied.  In an effort to find more opportunities to apply a functional approach, I’ve started using delegates a lot more in my code.  I am gradually starting to see patterns emerge where the delegates offer a cleaner solution.  Perhaps, it would be more accurate to say combining delegates.

I recently had what I thought would be a practical example to share.  Rather than getting into a long tangent about the context, I’m going to get to the point and keep the example as short as possible.  Hopefully, you will still see the benefit and the point.

I was working on some code to facilitate simple SELECT queries that automatically get mapped into an instance of a specified type.  Here is a simplified version of the relevant code. 

public class Query
    readonly string sql;
    readonly Func<IDataReader, object> load_results_from;

    public Query(string sql, Func<IDataReader, object> load_results_from)
        this.sql = sql;
        this.load_results_from = load_results_from;

    public object run_against(IDatabase database)
        using (var reader = database.execute_reader(sql))
            return load_results_from(reader);


As you can see, there is nothing really glamorous about this code.  It allows the consum