Tuesday, March 22, 2016

What are Fluent Interfaces?

What are they?
A fluent interface is an API facade that uses method chaining that preserves state throughout the method calls. This type of API can lead to more readable OO code because each method call returns a new class that contains the new state. Meaning the result of each call does not have to be stored in a variable and can be chained together.

When to use?
Functional programming has pipelining and higher order functions to achieve the readability win that fluent interfaces provide in OO languages. So, I think fluent interfaces are unnecessary in functional languages. Fluent interfaces can provide more readable code using method chaining in OO languages. Use them when your API needs to be simplified and you want it to read well.

Take this LINQ example:
[1; 2; 4]
  .Select(fun x -> x + 1)
  .Where(fun y -> y < 4)

There is a lot going on under the hood, but by simply looking at this code it is easy to tell what is supposed to happen.

How to implement?
To implement method chaining each method must return a new instance of a class taking into account the current state. A fluent interface is not necessarily just method chaining, so how to implement a fluent interface is specific to the domain space. We'll use a simple method chaining example here.

Here is a class with two actions.
type Counter = { Count: int } with
  member this.Increment : Counter = 
    { Count = this.Count + 1 }
  member this.Print : Counter = 
    printfn "Current Count = %i" this.Count
    { Count = this.Count }

Each action returns a new instance of the class and the method calls can be chained together.
{ Count = 3 }

The output of the above statement would be:
Current Count = 4
Current Count = 6
This example is trivial but this method can be used with complicated scenarios resulting in more readable code.

No comments:

Post a Comment