Some Functional Programming in C# 2.0

Well, the C# 3.0 beta 2 drop hit us last week and with it comes some nice functional programming constructs and syntax for the language we all know and love. I’ve been trying to learn more about the new toys ever since Microsoft shipped the first community preview, but it’s only recently and thanks to some helpful blogs I’ve been reading that it’s finally starting to click with me. Dustin Campbell’s post, A Higher Calling, was where things finally began to make sense. Much thanks to him for finally sitting me down and dropping some functional science on me, even if he didn’t do so directly, or for me in particular.

 I won’t rehash that article, but in short it introduces the concept of higher-order functions, which simply put are functions that either take other functions as input or return functions as an output. In the same way that functions allow you to abstract away the details of a particular task away from other code and make it resuable, higher-order functions let you abstract away entire algorithms at a higher level than just functions alone can. If that doesn’t make any sense, I have only my crude words to blame, but I hope that you’ll stick around for the example where things will hopefully get clearer. If this is all elementary to you and you’ve been writing pure functions since I was in diapers, then feel free to sit this one out.

C# has always allowed for this through the concept of delegates, but the syntax to use them was so verbose that it didn’t help make code much clearer or more concise, which are generally considered to be nice goals to have. C# 2.0 introduced anonymous methods and delegates, which made the syntax a little less trying, and C# 3.0 is bringing us anonymous types and lambdas which make it even terser. More terse. Simpler. The opposite of this description that I am currently typing. Smarter people than I have written some good articles on these topics so I’ll refer you to them for further and more entertaining reading.

So, I have a Windows service to run housekeeping processes for my employer, and this service processes files and sends their contents up to the database. It would be a perfect job for BizTalk to handle, but BizTalk costs an arm, a leg, and whatever other appendages you may have left over, and that’s another post. Suffice it to say that I’m having to make do with my own poor man code for now.  Databases and networks being what they are, sometimes they are down, sometimes they are too busy for you, and sometimes you’ve put the transaction log on the tiny partition. Bad things happen. You need to try, try again. So, peppered throughout the code, I have this in key areas:

FunctionalProgramming_Retry1

So, it loops until either the code completes successfully or it retries too many times, in which case it throws the exception necessitating the retry to a higher level. It gets the job done, except that I have to write this same code. A lot. Every time with a different spin on doSomeWork() or saveToDatabase(). I didn’t like it, but what could a mere mortal such as myself do? Enter functional programming.

FunctionalProgramming_HigherOrder

What I’ve done here is refactor the “retry” pattern that I use over and over again and made it a higher-order function that retries any function I pass into it a given number of times. In essence, it abstracts the concept of retrying into a neatly isolated function. How great is that? Now it becomes trivial to retry any piece of code I need, without having to write the same retry pattern each time I need it. A normal function in C# wouldn’t have let me do this, but functional programming via delegates lets me get away with tricks like this:

FunctionalProgramming_After

What makes the solution somewhat inelegant is the fact that it has to handle situations in which the retried code has a return value and times when it does not. Currently, having one delegate that takes a generic parameter for output works, but it requires shenanigans like passing in <object> when I have no intention of actually using the return value. C# 3.0 handles this more neatly, but that, too, is a story for another day.

So, any comments, criticism, and accolades are welcome. I’m fairly new to this concept, so it’s possible I have explained it incorrectly or done something ghastly, but so far it looks good to me.

3 Responses

  1. [...] I had the chance to read a blog by one of my former coworkers on the topic of code duplication and functional programming. I found the ideas there interesting; in many applications that I deal with there [...]

  2. >>C# 3.0 handles this more neatly, but that, too, is a story for another day.<<

    What do you mean exactly by this and how would you see it being implemented with your retry pattern?

  3. jamie,

    I published a new article to answer your question. Let me know what you think of the changes.
    http://anydiem.com/2008/02/27/some-functional-programming-in-c-30/

    -Sean

Leave a Reply