Puneet Varma (Editor)

Fluent interface

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide more readable code.

Contents

A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining ). Generally, the context is

  • defined through the return value of a called method
  • self-referential, where the new context is equivalent to the last context
  • terminated through the return of a void context.
  • History

    The term "fluent interface" was coined in late 2005, though this overall style of interface dates to the invention of method cascading in Smalltalk in the 1970s, and numerous examples in the 1980s. A common example is the iostream library in C++, which uses the << or >> operators for the message passing, sending multiple data to the same object and allowing "manipulators" for other method calls. Other early examples include the Garnet system (from 1988 in Lisp) and the Amulet system (from 1994 in C++) which used this style for object creation and property assignment.

    JavaScript

    There are many examples of JavaScript libraries that use some variant of this: jQuery probably being the most well known. Typically fluent builders are used to implement 'database queries', for example in https://github.com/Medium/dynamite :

    A simple way to do this in JavaScript is using prototype inheritance and `this`.

    Java

    The jOOQ library models SQL as a fluent API in Java

    The op4j library enables the use of fluent code for performing auxiliary tasks like structure iteration, data conversion, filtering, etc.

    The fluflu annotation processor enables the creation of a fluent API using Java annotations.

    The JaQue library enables Java 8 Lambdas to be represented as objects in the form of expression trees at runtime, making it possible to create type-safe fluent interfaces, i.e. instead of:

    One can write:

    Also, the mock object testing library EasyMock makes extensive use of this style of interface to provide an expressive programming interface.

    In the Java Swing API, the LayoutManager interface defines how Container objects can have controlled Component placement. One of the more powerful LayoutManager implementations is the GridBagLayout class which requires the use of the GridBagConstraints class to specify how layout control occurs. A typical example of the use of this class is something like the following.

    This creates a lot of code and makes it difficult to see what exactly is happening here. The Packer class, visible at http://java.net/projects/packer/, provides a Fluent mechanism for using this class so that you would instead write:

    There are many places where Fluent APIs can greatly simplify how software is written and help create an API language that helps users be much more productive and comfortable with the API because the return value of a method always provides a context for further actions in that context.

    C#

    C# uses fluent programming extensively in LINQ to build queries using the standard query operators. The implementation is based on extension methods.

    Fluent interface can also be used to chain a set of method, which operates/shares the same object. Like instead of creating a customer class we can create a data context which can be decorated with fluent interface as follows.

    C++

    A common use of the fluent interface in C++ is the standard iostream, which chains overloaded operators.

    The following is an example of providing a fluent interface wrapper on top of a more traditional interface in C++:

    D

    Because of the Uniform Function Call Syntax (UFCS) in D, method chaining is particularly easy. If you write

    and the type of x does not provide a toInt() member function, then the compiler looks for a free function of the form

    This enables chaining methods in a fluent way like this

    instead of this

    Ruby

    The Ruby language allows modifications to core classes. This enables a programmer to implement fluent interfaces natively.

    In Ruby strings are instances of a String class, by defining new methods to the String class which each returns strings, we natively allow chaining of methods. In the example below, we define three new methods: indent, prefix and suffix. Each returning a string and hence an instance of String that has the three defined methods.

    Scala

    Scala supports a fluent syntax for both method calls and class mixins, using traits and the with keyword. For example:

    Perl 6

    In Perl 6, there are many approaches, but one of the simplest is to declare attributes as read/write and use the given keyword. The type annotations are optional, but the native gradual typing makes it much safer to write directly to public attributes.

    PHP

    In PHP, one can return the current object by using the $this special variable which represent the instance. Hence return $this; will make the method return the instance. The example below defines a class Employee and three methods to set its name, surname and salary. Each return the instance of the Employee class allowing to chain methods.

    Python

    In Python returning `self` in the instance method is one way to implement the fluent pattern.

    Debugging & error reporting

    Single-line chained statements may be more difficult to debug as debuggers may not be able to set breakpoints within the chain. Stepping through a single-line statement in a debugger may also be less convenient.

    Another issue is that it may not be clear which of the method calls caused an exception, in particular if there are multiple calls to the same method. These issues can be overcome by breaking the statement into multiple lines which preserves readability while allowing the user to set breakpoints within the chain and to easily step through the code line by line:

    However, some debuggers always show the first line in the exception backtrace, although the exception has been thrown on any line.

    Logging

    One more issue is with adding log statements.

    E.g. to log the state of buffer after rewind() method call, it is necessary to break the fluent calls:

    Subclasses

    Subclasses in strongly typed languages (C++, Java, C#, etc.) often have to override all methods from their superclass that participate in a fluent interface in order to change their return type. For example, in Java:

    Languages that are capable of expressing F-bound polymorphism can use it to avoid this difficulty. E. g. in Java:

    Note that in order to be able to create instances of the parent class, we had to split it into two classes — AbstractA and A, the latter with no content (it would only contain constructors if those were needed). The approach can easily be extended if we want to have sub-subclasses (etc.) too:

    References

    Fluent interface Wikipedia