Fluent Interface Helper (C#)

I’m practicing my C# so I thought I would take some of my most complex code and convert (most) of it by hand. In previous posts I explored how to make a fluent interface. I had to use lambdas, delegates and a whole lot of custom generics. It was a lot of fun. Here is how to use it in C# and a link to browse the code.

Let’s imagine that you have a collection of people.

List People = new List 
    new Person(){ name="Bentley", birthDate=new DateTime(1963, 3, 7)},
    new Person(){ name="Christy", birthDate=new DateTime(1973, 9, 19)},
    new Person(){ name="Benjamin", birthDate=new DateTime(2001, 9, 19)}

And let’s Imagine that you wanted to get a list of the people who’s name begins with the letter B and were borne sine 2000. You might do the following:

IEnumerable q = People.Where(p => p.name.StartsWith("B")).Where(p => p.birthDate > new DateTime(2000, 1, 1));

Which certainly gets the job done.

Now imagine that you are responsible for creating an maintaining a large list of business rules that look like this. Oh, and we might have some business analysts write the rules to help you out. Suddenly all the p => gets in the way of readability and sharing the task with less technical people.

One solution is a fluent interface. It’s a little more readable. Here is the same query done fluently.

PersonList q = People.Name().StartsWith("B").BirthDate().Greater(new DateTime(2000,1,1));

What do you think? Is it worth adding some extra code to clean up the text?

You can browse all the code or get a copy with Subversion at: svn checkout https://bentleys-code-samples.googlecode.com/svn/samples/FluentHelper FluentHelper