Month: June 2010

How to write fluent interface with C# and Lambda.

Last week I had a nice discussion in the office about “how to write fluent interface” and I have found a couple of articles over the internet about that. As usual I disagree with some of them and, as usual, my friend Mauro Servienti (MVP C#) has a nice article about it, unfortunately in Italian. He just gave me the startup input.

If you think about the Fluent Interface, it is just a trick that you use with C# in order to cheat the intellisense of Visual Studio and in order to create a nice style for your code. Of course there is a specific way to write fluent interface.

Let’s make a short sample. The classic Person class and the factory pattern.

We have a class which represents the Person Entity and has some common properties.


Very easy. Now, in a normal world you would have something like this, in order to create a new instance of a class person.

First way, the classis way:

Classic Person Factory
  1. public class PersonFactory
  2. {
  3.     public static Person CreatePerson(string firstName, string middleName, string lastName)
  4.     {
  5.         var person = new Person
  6.         {
  7.             FirstName = firstName,
  8.             MiddleName = middleName,
  9.             LastName = lastName
  10.         };
  11.         return person;
  12.     }
  13. }

This code is classic and very verbose. If you want to use it the syntax would be something like this:

Create Person
  1. var person = PersonFactory.CreatePerson(“Raffaele”, string.Empty, “Garofalo”);


Now, if we want to add an address to this person we need an additional like of code like this one, and of course a new factory for the class person or a new method in the person factory … whatever …

Create Address
  1. var address = PersonFactory.CreateAddress(“1st Lane”, “Main Road”, “Hamilton”, “Bermuda”, “HM10”);
  2. person.Addresses.Add(address);


First of all, here we have a big problem. All the parameters are strings. So, if we don’t explain in a proper verbose way each parameter, the developer that will use our factory won’t be able to know what to write in each parameter. Second thing, if we don’t use C# 4 we have to specify each parameter value anyway … Finally we are avoiding a nice readability in our code.

The first step for a fluent interface.

I saw a lot of code around the web but a lot of people forget about the name of this technique … The name is Fluent Interface so this means that probably we should add some interfaces in our code in order to have a good result. Well VS 2010 is able to create an interface from a class just with a couple of clicks … And this is the final result:


Now we need to translate each method in a Fluent method. Let’s start with the class person. What I am doing is an interface for my Factory and two methods, one for the Factory initialization, where we initialize a new instance of the class person and one to finalize it, where we will return the current instance of that class. Of course we need also the methods to add some values to the person properties. Look at the UML:


At here is the code:

  1. public interface IPersonFactory
  2. {
  3.     IPersonFactory Initialize();
  4.     IPersonFactory AddFirstName(string firstName);
  5.     IPersonFactory AddLastName(string lastName);
  6.     IPersonFactory AddMiddleName(string middleName);
  7.     IPerson Create();
  8. }


And this is the implementation:

  1. public class PersonFactory : IPersonFactory
  2. {
  4.     private IPerson person = null;
  6.     public IPersonFactory Initialize()
  7.     {
  8.         person = new Person();
  9.         return this;
  10.     }
  12.     public IPersonFactory AddFirstName(string firstName)
  13.     {
  14.         person.FirstName = firstName;
  15.         return this;
  16.     }
  18.     public IPersonFactory AddLastName(string lastName)
  19.     {
  20.         person.LastName = lastName;
  21.         return this;
  22.     }
  24.     public IPersonFactory AddMiddleName(string middleName)
  25.     {
  26.         person.MiddleName = middleName;
  27.         return this;
  28.     }
  30.     public IPerson Create()
  31.     {
  32.         return person;
  33.     }
  34. }


So now we start to have a FluentInterface capability in our code.

Code Snippet
  1. var person = new PersonFactory()
  2.                 .Initialize()
  3.                 .AddFirstName(“Raffaele”)
  4.                 // we can skip this line now …
  5.                 .AddMiddleName(string.Empty)
  6.                 .AddLastName(“Garofalo”)
  7.                 .Create();


Very well done but we still have a problem here. We are not giving a constraint to the developer that will use our fluent syntax. Let’s say that we are working with a retarded colleague, nobody can prohibit him to write something like this:

Wrong Person
  1. var wrongPerson = new PersonFactory().Create();


In this case he will get a nice NullReferenceException because if he doesn’t call the method Initialize the factory won’t create a new instance of the class person … So how can we add a constraint to our interface? Very simple, we need 3 interfaces and not only one anymore. We need IInitFactory, IPersonFactory and ICreateFactory.

Let’s see the code:

  1. public interface IPersonFactory
  2. {
  3.     IPersonFactory AddFirstName(string firstName);
  4.     IPersonFactory AddLastName(string lastName);
  5.     IPersonFactory AddMiddleName(string middleName);
  6.     IPerson Create();
  7. }


The IPersonFactory now will not be in charge anymore of creating a new instance of the class person, it will just be in charge of working with it. We will use dependency injection to inject a new instance. Let’s the concrete implementation of this factory:

Person Factory refactored
  1. public class PersonFactory : IPersonFactory
  2. {
  4.     private IPerson person = null;
  6.     public PersonFactory(IPerson person)
  7.     {
  8.         this.person = person;
  9.     }
  11.     public IPersonFactory AddFirstName(string firstName)
  12.     {
  13.         this.person.FirstName = firstName;
  14.         return this;
  15.     }
  17.     public IPersonFactory AddLastName(string lastName)
  18.     {
  19.         this.person.LastName = lastName;
  20.         return this;
  21.     }
  23.     public IPersonFactory AddMiddleName(string middleName)
  24.     {
  25.         this.person.MiddleName = middleName;
  26.         return this;
  27.     }
  29.     public IPerson Create()
  30.     {
  31.         return this.person;
  32.     }
  33. }


Now we need an orchestrator. Somebody that will be visible outside and will be in charge of giving to the fluent syntax a static flavor (we want to avoid the new Factory() syntax …) and that will return a PersonFactory ready to work …

Person Fluent Factory
  1. public static class PersonFluentFactory
  2. {
  3.     public static IPersonFactory Init()
  4.     {
  5.         return new PersonFactory(new Person());
  6.     }
  7. }


And now Visual Studio will follow our rules …

Parallels Picture

Parallels Picture 1

Final Step, Lamba expression for a cool syntax.

Ok this is cool and it works like we want but … it is really time consuming. We want a fluent interface and that’s fine but if you a domain with 100 entities and more or less 100 factories, can you imagine the pain in the neck in order to adopt this pattern all over?? Well this is the reason you should study more in depth C#!! If you didn’t know, there is a cool syntax future in C# called Lambda Expressions. If you don’t know what I am talking about, have a look here.

First of all we need a generic interface for our factory with only two methods, one to add a value to a property and one to return the current instance of the entity created by the factory.

  1. public interface IGenericFactory<T>
  2. {
  3.     IGenericFactory<T> AddPropertyValue(Expression<Func<T, object>> property, object value);
  4.     T Create();
  5. }

Then following the same logic of the previous steps we need a concrete implementation but using generics and lambda expressions (I really love this part).

Generic Factory &lt;T&gt;
  1. public class GenericFactory<T> : IGenericFactory<T>
  2. {
  3.     T entity;
  5.     public GenericFactory(T entity)
  6.     {
  7.         this.entity = entity;
  8.     }
  10.     public IGenericFactory<T> AddPropertyValue(Expression<Func<T, object>> property, object value)
  11.     {
  12.         PropertyInfo propertyInfo = null;
  13.         if (property.Body is MemberExpression)
  14.         {
  15.             propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
  16.         }
  17.         else
  18.         {
  19.             propertyInfo = (((UnaryExpression)property.Body).Operand as MemberExpression).Member as PropertyInfo;
  20.         }
  21.         propertyInfo.SetValue(entity, value, null);
  23.         return this;
  24.     }
  26.     public T Create()
  27.     {
  28.         return this.entity;
  29.     }

And the Fluent Factory, now generic, in this way:

Code Snippet
  1. public static class GenericFluentFactory<T>
  2. {
  3.     public static IGenericFactory<T> Init(T entity)
  4.     {
  5.         return new GenericFactory<T>(entity);
  6.     }
  7. }


The final syntax will be this one:

Code Snippet
  1. var person = GenericFluentFactory<Person>
  2.     .Init(new Person())
  3.     .AddPropertyValue(x => x.FirstName, “Raffaele”)
  4.     .AddPropertyValue(x => x.LastName, “Garofalo”)
  5.     .Create();


Ta da!! One generic factory with syntax constraints to create as many entities as you want! And the smart developer that is working with you won’t be able to complain at all.

Final notes.

We can make this code better by:

  • Adding a custom type reflected by the property we are using, so you won’t be able to add an integer value to a property of type string and so on …
  • Remove that ugly .Init(new Person()) using an IoC engine or a new constraint to our class, of course in this case you must provide classes with at least 1 parameters less constructor.

That’s it! Have fun!

WebHost4Life, the worst Hosting Service.

Oh, I am so glad that after 15 days of troubles and problems I am finally able to post again from my blog.

An this is just one of the new important news! But let’s start to shame on WebHost4Life.

I want to let you know that I am the owner of this domain, starting from the far 2003 and I had various Hosts in these years but I never had such a kind of problem.

Around January 2010 the crappy WebHost4Life started the tedious migration under the new Control Panel but this is not the true. They started to migrate manually user by user. I tried to post this migration until 15 days ago but then, when I renewed my subscription with them I started to have problems over problems.

First, the domain totally disappeared from my control panel, at that point I was not able anymore to receive e-mails, to host my blog and more … After 10 open tickets and a lot of money spent in calling them, I decided to block my payment with Paypal and open a formal claim.

You know what happened after that? They simply wiped everything. My files, my account, my e-mails and my SQL server. The only way to get back these files, that are mine, was to pay them an upfront of 143 USD.

After that they simply putted online again an old version of my blog and a mess in the database. All the emails are gone! I am sure about that because I use Subtext 2.2 and the version they restored was the 1.9. I did the migration to the version 2 more than 6 months ago ….

Now everything is fine for the simple reason that I moved to a new provider. Now I am using and it’s pretty cool. In less than 1 day they contacted the registrar, changed my DSN and made everything working. I have also a cool IMAP provider for my mail accounts.

I am trying now to open a formal claim with all the other users that had the same problem I had as WebHost4Life doesn’t deserve to be a web host for the crap they are doing all around.

What I can suggest to you, if you are under them is to look for a new host and try to postpone the migration to the new platform as far as you can. Also remember to backup everything as it seems that they are totally incompetent …

There is still plenty of work to do. I lost most of my screenshots and files so you will find some problems reading my articles but I have a lot of backups so don’t worry, I will replace everything in few weeks.

Stay tuned as we are going back to talk about WPF and Prism again in few days. I have plenty of posts to share with you.