In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.

Implementation A fluent interface is commonly implemented through method chaining to achieve method cascading in languages that do not provide cascading natively. This is typically done by having each method return the object on which it was invoked, often referred to as this or self. More abstractly, a fluent interface maintains the instruction context of a subsequent call within a chain, where the context is generally: defined through the return value of the preceding method, self-referential, where the new context is equivalent to the previous one, or terminated by returning a void context. A fluent interface involves more than method chaining alone; it also entails designing the API so that chained calls read like a domain-specific language (DSL), often incorporating techniques such as nested functions and careful object scoping.

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.

Examples

C#

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

using System.Collections.Generic;

// An English-to-French dictionary of animal names Dictionary<string, string> translations = new() { {"cat", "chat"}, {"dog", "chien"}, {"fish", "poisson"}, {"bird", "oiseau"}

// Find translations for English words containing the letter "a", // sorted by length and displayed in uppercase IEnumerable<string> query = translations .Where(t => t.Key.Contains("a")) .OrderBy(t => t.Value.Length) .Select(t => t.Value.ToUpper());

// The same query constructed progressively: IEnumerable<string> filtered = translations.Where(t => t.Key.Contains("a")); IEnumerable<string> sorted = filtered.OrderBy(t => t.Value.Length); IEnumerable<string> finalQuery = sorted.Select(t => t.Value.ToUpper()); Fluent interface can also be used to chain a set of methods, which operate on/share the same object. Instead of creating a customer class, we can create a data context which can be decorated with fluent interface as follows. // Defines the data context class Context { public string FirstName { get; set; } public string LastName { get; set; } public string Sex { get; set; } public string Address { get; set; } }

class Customer { private Context _context = new(); // Initializes the context

// set the value for properties public Customer FirstName(string firstName)

_context.FirstName = firstName; return this;

public Customer LastName(string lastName)

_context.LastName = lastName; return this;

public Customer Sex(string sex)

_context.Sex = sex; return this;

public Customer Address(string address)

_context.Address = address; return this;

// Prints the data to console public void Print()

Console.WriteLine($"First name: {_context.FirstName} \nLast name: {_context.LastName} \nSex: {_context.Sex} \nAddress: {_context.Address}");

class Program { static void Main(string[] args)

// Object creation Customer c1 = new(); // Using the method chaining to assign & print data with a single line c1.FirstName("John") .LastName("Doe") .Sex("Male") .Address("123 Example St, Orlando FL 12345") .Print();

The .NET testing framework NUnit uses a mix of C#'s methods and properties in a fluent style to construct its "constraint based" assertions: using System;

Assert.That(() => 2 * 2, Is.AtLeast(3).And.AtMost(5));

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

In this example which demonstrates the builder pattern, the class Computer has an internal Builder class used to construct a Computer through a fluent API, while making the constructor private and having the build() method return a smart pointer to the Computer object.

import std;

using std::string; using std::unique_ptr;

class Computer { private: string cpu; string gpu; int ram; // default value int storage; // default value

Computer(string cpu, string gpu, int ram, int storage): cpu{std::move(cpu)}, gpu{std::move(gpu)}, ram{ram}, storage{storage} {} public: ~Computer() = default;

void showSpecs() { std::println("Computer specs:"); std::println(" CPU: {}", cpu); std::println(" GPU: {}", gpu); std::println(" RAM: {} GB", ram); std::println(" Storage: {} GB", storage);

class Builder { private: // Builder is given default parameters string cpu = "Generic CPU"; string gpu = "Integrated Graphics"; int ram = 16; int storage = 512; public: Builder() = default;

Builder& ofCpu(string cpu) noexcept { this->cpu = std::move(cpu); return *this;

Builder& ofGpu(string gpu) noexcept { this->gpu = std::move(gpu); return *this;

Builder& withRam(int gb) noexcept { ram = gb; return *this;

Builder& withStorage(int gb) noexcept { storage = gb; return *this;

unique_ptr<Computer> build() { return unique_ptr<Computer>(new Computer(cpu, gpu, ram, storage));

int main() { unique_ptr<Computer> myComputer = Computer::Builder() .ofCpu("AMD Ryzen 7") .ofGpu("NVIDIA RTX 4070") .withRam(32) .withStorage(1000) .build();

myComputer->showSpecs(); }

Java An example of a fluent test expectation in the jMock testing framework is:Martin Fowler, "FluentInterface", 20 December 2005

mock.expects(once()).method("m").with( or(stringContains("hello"), stringContains("howdy")) ); The jOOQ library models SQL as a fluent API in Java: Author author = AUTHOR.as("author"); create.selectFrom(author) .where(exists(selectOne() .from(BOOK) .where(BOOK.STATUS.eq(BOOK_STATUS.SOLD_OUT)) .and(BOOK.AUTHOR_ID.eq(author.ID)) ) );

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: Customer customer = new Customer(); customer.property("name").eq("John") One can write: method<Customer>(customer -> customer.getName() == "John")

Also, the mock object testing library EasyMock makes extensive use of this style of interface to provide an expressive programming interface. Collection mockCollection = EasyMock.createMock(Collection.class); EasyMock .expect(mockCollection.remove(null)) .andThrow(new NullPointerException()) .atLeastOnce();

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. import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField;

GridBagLayout gl = new GridBagLayout(); JPanel p = new JPanel(); p.setLayout(gl);

JLabel l = new JLabel("Name:"); JTextField nm = new JTextField(10);

GridBagConstraints gc = new GridBagConstraints(); gc.gridx = 0; gc.gridy = 0; gc.fill = GridBagConstraints.NONE; p.add(l, gc);

gc.gridx = 1; gc.fill = GridBagConstraints.HORIZONTAL; gc.weightx = 1; p.add(nm, gc);

This creates a lot of code and makes it difficult to see what exactly is happening here. The Packer class provides a fluent mechanism, so you would instead write: import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField;

JPanel p = new JPanel(); Packer pk = new Packer(p);

JLabel l = new JLabel("Name:"); JTextField nm = new JTextField(10);

pk.pack(l).gridx(0).gridy(0); pk.pack(nm).gridx(1).gridy(0).fillx();

There are many places where fluent APIs can 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.

JavaScript/TypeScript

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 the Dynamite client library:

// getting an item from a table client.getItem('user-table') .setHashKey('userId', 'userA') .setRangeKey('column', '@') .execute() .then(function(data) { // data.result: the resulting object })

A simple way to do this is using prototype inheritance and this, such as in this TypeScript example:

// example from https://schier.co/blog/2013/11/14/method-chaining-in-javascript.html

class Kitten { public name: string; public color: string;

constructor() { this.name = 'Garfield'; this.color = 'orange';

public setName(name: string): this { this.name = name; return this;

public setColor(color: string): this { this.color = color; return this;

public save(): this { console.log(`saving ${this.name}, the ${this.color} kitten`); return this;

// use it let salem = new Kitten() .setName('Salem') .setColor('black') .save();

Scala

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

class Color { def rgb(): Tuple3[Decimal] } object Black extends Color { override def rgb(): Tuple3[Decimal] = ("0", "0", "0"); }

trait GUIWindow { // Rendering methods that return this for fluent drawing def set_pen_color(color: Color): this.type def move_to(pos: Position): this.type def line_to(pos: Position, end_pos: Position): this.type

def render(): this.type = this // Don't draw anything, just return this, for child implementations to use fluently

def top_left(): Position def bottom_left(): Position def top_right(): Position def bottom_right(): Position }

trait WindowBorder extends GUIWindow { def render(): GUIWindow = { super.render() .move_to(top_left()) .set_pen_color(Black) .line_to(top_right()) .line_to(bottom_right()) .line_to(bottom_left()) .line_to(top_left())

class SwingWindow extends GUIWindow { ... }

val appWin = new SwingWindow() with WindowBorder appWin.render()

Raku

In Raku, 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.

class Employee { subset Salary of Real where * > 0; subset NonEmptyString of Str where * ~~ /\S/; # at least one non-space character

has NonEmptyString $.name is rw; has NonEmptyString $.surname is rw; has Salary $.salary is rw;

method gist { return qq:to[END]; Name: $.name Surname: $.surname Salary: $.salary END

my $employee = Employee.new();

given $employee { .name = 'Sally'; .surname = 'Ride'; .salary = 200; }

say $employee;

# Output: # Name: Sally # Surname: Ride # Salary: 200

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.

<?php declare(strict_types=1);

final class Employee { private string $name; private string $surname;