After Thought

Posts Tagged ‘Fluent Interface

Fluent Interface

leave a comment »

The term Fluent interface was first coined by Martin Fowler and Eric Evans. Refer to this article by Fowler. There are a lot of write-ups on the web on this topic including Josh Flanagan’s blog which was my first introduction to the topic. According to the definition in wikipedia, fluent interface is implemented using method chaining where the new context is same as the last context.
Below is an example to add car accessories. When we buy a new car, we tend to add accessories like leather seats, power windows etc to the car. We can implement it using fluent interfaces to make it look more readable and clean.

public class Car
{
	public Car AddLeatherSeats()
	{
		//Add Leather Seats
		return this;
	}

	public Car AddPowerWindows()
	{
		//Add Power Windows
		return this;
	}
}

So now if you have an instance of Car named instanceOfCar you can simply say

instanceOfCar
  .AddLeatherSeats()
    .AddPowerWindows();

Extension methods lets us implement fluent interface on existing objects. Suppose, we need a method to add MoonRoof, we can simply add an extension method.

public static class CarAccessoriesExtensions
{
	public static Car AddMoonroof(this Car car)
	{
		//Add Moonroof
		return car;
	}
}

Now you can say,

instanceOfCar
  .AddLeatherSeats()
    .AddPowerWindows()
      .AddMoonroof();

One thing to keep in mind here is we shouldn’t use fluent interfaces everywhere.  We have to use it in places where its addition makes code more readable by taking out the noise. It may be a good conversation to have on when and where fluent interfaces should be used. Any comments and suggestions would be great.

Written by shashankshetty

March 9, 2009 at 4:59 pm