Fluent Interfaces

By: Dan
DOWNLOAD AS PDF

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

latest news

01

5 signs your company needs an ERP

An ERP system captures information from all departments, and it may be time for you to implement it within your organization. Here are 5 signs that make it clear your business will benefit from an ERP system.

02

7 Benefits of an ERP System For Your Business

ERPs manage the core processes of an organization – from HR to sales to finance – and house all the data. Many ERPs also offer increased visibility, analytics, and efficiency across the company. Let’s explore some of the benefits of running your business on an ERP system

03

8 Benefits to Adopting DevOps into your Organization

Under DevOps, a “product-first” approach, companies align development projects with the business goals of operations so teams can jointly build, test, release, and maintain new digital applications more frequently and more efficiently. What benefits does DevOps offer?

Copyright© 2018 alligatortek. All rights reserved.