Fluent Interfaces

| By: Dan

The fluent interface is an object-oriented coding concept introduced by Martin Fowler and Eric Evans in 2005. Fluent interfaces are constructed using method chaining. If you have used LINQ dot(.) syntax, you have used a fluent interface.

var result = MyList.Where(l => l.Value > 200).OrderBy(l => l.CreateDate).Take(5).Select(l => l.Item);

Fluent interfaces solve two programming issues. First, they make the code more readable and easy to understand. This makes it easier to make changes later. It also makes it easier for new developers to get up to speed quickly with your domain’s API.

Second, fluent interfaces can be used to force the programmer to perform steps in the correct order. If objects are set up with a fluent interface correctly, a programmer will not able to call a method unless the required precursor method has been called first.

To better illustrate the advantage of a fluent interface, see the code snippets below. The first shows the creation of an order with some order detail lines. The second shows the same process, but implemented using a fluent interface.

Non-Fluent

var customer = new Customer();

var order = new Order(customer);

OrderLine ol = new OrderLine { ProductId = 111, Quantity = 3 };

order.OrderLines.Add(ol);

OrderLine ol = new OrderLine { ProductId = 222, Quantity = 4 };

order.OrderLines.Add(ol);

var orderProcess = new OrderProcessor();

orderProcessor.Process(order);

 

Fluent

var customer = new Customer();

customer.NewOrder()
.WithLine(111, 3)
.WithLine(222, 4)
.Process();

The fluent code above takes less time to code and is much easier to read and follow.

Fluent interfaces require more planning and work to implement. But, the advantages later on are worth it.

For more information on fluent interfaces:

http://martinfowler.com/bliki/FluentInterface.html