Fluent design and immutable objects

1 Dec, 2026 · 13 min read
Contents

A fluent interface lets us chain calls on an object, and it costs almost nothing to provide. Immutable objects fix the biggest of its deficiencies and let us save intermediate states and build on them, at a cost in memory. Together they package functionality with a natural developer experience. I think every developer who designs APIs should know these techniques, especially for chatty APIs, with many methods and properties in logical groups.

Fluent design and immutable objects

This is the sixth post in a series on API design. Ergonomics and cognitive load opened its second half, about how to expose an API, and argued that how an API feels in use is part of its design. This post takes up the first two techniques for it.

Fluent interfaces: cheap and common

Setters and actions change the state of an object, and usually they return undefined. A fluent interface makes them return this, the object itself. Here is a small query builder that records clauses:

class Query {
  #clauses = [];
  from(table) {
    this.#clauses.push(['from', table]);
    return this;
  }
  where(condition) {
    this.#clauses.push(['where', condition]);
    return this;
  }
  // ... orderBy(), limit(), and so on ...
}

Because every method returns the same object, the next call can go on the same line:

// one call per line
const query = new Query();
query.from('users');
query.where('active');
query.orderBy('name');

// or a fluent chain
const chained = new Query()
  .from('users')
  .where('active')
  .orderBy('name');

The chain cuts down on repetition and visual noise, which improves readability, and a sequence of steps reads as one linear chain. More importantly, a chain is an expression, so intermediate objects can stay nameless. Here we add a layer to a canvas and a rectangle to the layer:

const rect = canvas.addLayer()
  .setOpacity(0.5)
  .addRect(40, 20)
  .fill('red')
  .stroke('black')
  .rotate(45);

addLayer() and addRect() return new objects, and the fluent setter and actions return this, so all of them fit in one expression. Without the fluent style, the same code needs two names:

const layer = canvas.addLayer();
layer.setOpacity(0.5);
const rect = layer.addRect(40, 20);
rect.fill('red');
rect.stroke('black');
rect.rotate(45);

Arguably the second version is less readable. A reader has to check whether layer is used anywhere else, and whether anything uses rect between fill() and stroke(). In the chain both answers are obvious: nothing can run between two links, and the layer has no name that other code could use. Sometimes a name helps us understand the purpose of an intermediate object, but in many cases transient objects should stay nameless and transient.

The cost for an implementer is one line per method. A caller can ignore it at no cost: the same methods work one call per line, as before. The fluent style is nice and virtually free.

We find it frequently in the wild. jQuery’s addClass() returns the same jQuery object, so $('.item').addClass('active').show() works. In Express, res.status() returns the response, so res.status(404).json(body) sets the status and sends the body. The query builder of Knex chains where(), orderBy(), and limit() much like our Query. Even JavaScript’s arrays do it: sort() and reverse() return the array they changed.

A chain stops at a method that returns a plain value, such as a getter or a computation. So the fluent part of an API is limited to the methods that change state and have no other value to return. A method that changes state and has a result of its own is a problem we come back to below.

Where fluent falls short

Every link a fluent method adds is the object it was called on, and a program can save any link in a variable. Let’s build a query for active users and two more queries on top of it:

const active = new Query().from('users').where('active');
const admins = active.where('admin');
const recent = active.orderBy('date').limit(10);

We meant three queries, and we got one object that all three variables refer to. It selects active admins, sorted by date, at most ten of them. admins changed when we built recent, and active changed twice.

Here the problem is easy to see, because the three lines sit together. This interdependence of links is the biggest deficiency of the fluent style. Imagine that we pass active to a function, and at some point, maybe asynchronously much later, the function modifies it. Suddenly our main object behaves in unexpected ways, and we have to find out why. That violates locality: to know what active holds at a given line, we have to know everything that touched it before, which makes debugging hard. Other mutable objects have the same problem, but I’ve noticed that the fluent style lends itself to such bugs. Mutable objects are error-prone by nature, and they need strict discipline about who can mutate what.

Knex knows the problem and provides clone(), which its docs describe as “useful for re-using partial query snippets in other queries without mutating the original.” The discipline is to remember to call it. JavaScript’s arrays have the same problem: const sorted = list.sort() sorts list too, because sort() returns the array it sorted. The language later added toSorted(), which returns a sorted copy.

Immutable objects: save and build on intermediate states

An immutable object never changes after it is built. Its setters and actions stay, but each returns a new object: a copy of the original with the requested change. Our fluent methods return that copy instead of this:

class Query {
  #clauses;
  constructor(clauses = []) {
    this.#clauses = clauses;
  }
  #add(clause) {
    return new Query([...this.#clauses, clause]);
  }
  from(table) {
    return this.#add(['from', table]);
  }
  where(condition) {
    return this.#add(['where', condition]);
  }
  // ... orderBy(), limit(), and so on ...
}

The calling code stays the same, and the same three lines now build three queries. active selects active users, admins selects active admins, and recent selects the ten most recent active users. Logically a caller sees the same API. But now we can save any link and keep its state for later. We can use one as a default and fork from it at will, and building on a fork leaves the original as it was.

Saved objects need no copying either. An immutable object is shared by reference: any holder can read it and build on it, and none can change it for the others. That fixes the biggest deficiency of the fluent style and settles many questions about who can mutate what.

Immutability has two consequences for API design. First, methods split into read-only ones and state-modifying ones. A reader returns a value, and a modifier returns a new object. The split is a good habit for any API, and C++ supports it in the language with const methods. Second, every state-modifying method has a return value, the new object, so a modifier with no other result can be chained. Chains still end at readers, as before.

In functional terms, each modifier is a pure function from an old object to a new one, and a fluent chain is a pipeline of such functions. The same technique serves object-oriented and functional code alike.

Exotic goto showed the opposite case. A paused generator keeps its state inside, and next() destroys that state to produce the next one. So a generator cannot be copied, and each suspension point can be reached only once. If that state were an immutable value, we could keep any suspension point and resume from it as often as we liked.

When a modification has a result

Immutability fixes the biggest deficiency of the fluent style. Two more problems remain. They are common problems of object-oriented design, and we meet them without fluent or immutable objects. The fluent style highlights them: it makes us think in methods, and some operations make little sense as methods.

The first is a modification with a result of its own. A method returns one value, so a fluent method returns either this or its result. An immutable method already returns the new object, so its result needs another way out. JavaScript’s splice() shows the choice. It removes elements from an array, can insert new ones, and returns an array of the removed elements. My understanding is that the thinking went like this: it is the only way to get them, while the changed array can always be read back by its name. It works, but it breaks a chain: the returned value is an array too, and it is a different array. Returning the updated array would be more logical, and in real code the removed elements are rarely needed:

// a fantasy spliceThis() that returns `this`
const a = array1.concat(array2)
  .spliceThis(3, 1, 2, 3)
  .map(x => x + 1);

// real code
const namedTemp = array1.concat(array2); // needed below
namedTemp.splice(3, 1, 2, 3); // the returned array is dropped
const a = namedTemp.map(x => x + 1); // hence the name

The language later added toSpliced(), the copying version of splice(). It returns the changed copy and leaves the removed elements out, so it chains the way spliceThis() would.

One possible fix for splice() itself is a named property on the returned array that refers to the modified original. Then we can still chain when we don’t want the removed elements:

// a hypothetical `array` property
const a = array1.concat(array2)
  .splice(3, 1, 2, 3).array
  .map(x => x + 1);

For our own methods, I usually return a compound value with two properties. value is what the operation itself produces. The modified object is named after its type, as array is above, so a list returns {value, list}. A caller can chain on list and ignore the value, or save and use both:

// chain on the new list, ignore the value
const next = list.removeAt(3).list.add(42);

// or keep both
const {value: removed, list: rest} = list.removeAt(3);

The second problem is more common: an operation on several objects with no clear leader. When an operation modifies several objects, we have to choose what to return and how. Usually we return a compound value, as above, and sometimes we pick one object and return it. Picking a leader is a choice of its own: the same move can be a method of either list, and I’ve seen both in the wild, sometimes on one class to cover both directions:

// which list leads, and what comes back?
const a = from.moveTo(to, item);
const b = to.moveFrom(from, item);

// no leader to pick: a function
const [nextFrom, nextTo] = move(from, to, item);

// or a static method
const [newFrom, newTo] = List.move(from, to, item);

Two lists are the simple case. Imagine an action that updates five objects in a coordinated way and builds no single object as its result. Which of the five should own the method, and what should it return?

Object-oriented programming is about packaging, and it favors operations on a single main object. The algorithms underneath are still functional code, even when we compose them from methods. When an action has no main object, it is usually best framed as a stand-alone function or, in some cases, a static method.

Worked example: console-toolkit

My console-toolkit styles terminal text with both techniques. A style is built by a chain of getters, starting from the base object style, and every link returns a new style object. A saved link is a preset we can build on:

import {style, c} from 'console-toolkit/style.js';

const alert = style.bold.bright.yellow;
const warn = alert.bg.dark.blue;
const error = alert.bg.red;

console.log(warn.text('Disk is almost full.'));
console.log(error.text('Disk is full.'));
console.log(alert.text('No background here.'));

The chain reads as a description: bold, bright yellow, on dark blue. Immutability makes each result safe to keep. alert is still bold bright yellow after both forks, warn and error are independent, and any of them can be a constant reused across a program. The docs say that style objects “are frozen with Object.freeze(), so they can be saved and reused freely.” The same names work inside a tagged template:

console.log(c`{{bold}}Hello, {{bright.cyan}}world!`);

bg, bright, and dark in these chains are views: objects that expose only the operations that make sense at that point of a chain. They are the subject of the next post in this series.

The cost: memory, and what it takes to cut it

The downside of immutable objects is more memory load. Every modification creates a new object, even a small one, and the garbage collector has to clean up after it. The technique needs no language support, but it may need some discipline and profiling. I use it when it has clear benefits over potential performance problems.

There is a cost in syntax and familiarity too:

// mutable
x.a += 2;

// immutable
const x2 = x.setA(x.getA() + 2);

The immutable form is longer and harder to read, and it creates an object for a two-character change. A few changes in a row create an object each, and we keep only the last.

It would be nice to have a transaction of some sort that produces a modified object. Without language support, we can make one an API. clone() copies an object, makes the copy mutable, passes it to a callback, and returns it:

const x2 = x.clone(draft => {
  draft.a += 2;
  draft.b = 42;
  draft.c = (draft.a + draft.b) * 2;
  draft.setA(99).incB(1);
});

Inside the callback the familiar syntax works, and setters return this, so fluent chains work as well. No intermediate objects are created: one new object per transaction. One rule remains, and it takes discipline: the draft must not escape the callback. Stored somewhere and modified later, it would change the result after clone() returned it.

Libraries have shipped the same idea, and some enforce that rule. Clojure has transients, which throw an exception on any use after we make them persistent. Immutable.js has withMutations(), which applies a batch of mutations to a temporary mutable copy. Immer’s produce() passes a draft to a callback and freezes the result.

The best way is to detect transient, unshared objects and modify them in place, creating copies only when an object is visible to others. That is a job for a compiler or an interpreter, and some functional languages do it: Lean 4 and Koka update a value in place when its reference count shows a single holder. In JavaScript, clone() is the manual version.

To make an object truly immutable, we can use Object.freeze(). The price is paid at creation only: on Node 26.8 a four-field object takes 10 ns to build and 57 ns to build and freeze, while reads and method calls on the frozen object measure the same as on a plain one (measured with nano-bench, bench files and results). Bun and Deno show the same shape, with Bun’s freeze about three times cheaper. For objects built once and reused, that is free, and console-toolkit freezes its style objects. Freezing has one conflict: it rules out an object that replaces its own methods as its state changes, a technique for a later post in this series.

Summary

  • A fluent interface returns this from setters and actions, so calls chain into one expression that keeps intermediate objects nameless. It is cheap to build, free to ignore, and common in the wild.
  • The biggest deficiency of a mutable fluent chain: every fluent link is the object it was called on, so code we don’t observe can change a saved link, even asynchronously, much later.
  • An immutable object returns a new object from every modification. The same chains then build values we can save, share, and build on, and readers split cleanly from modifiers.
  • A modification with a result of its own breaks a chain in both styles. A compound value like {value, list} keeps the chain going, and an operation on several objects with no leader is usually best as a stand-alone function.
  • Together the two techniques package functionality with a natural developer experience. I think every developer who designs APIs should know them, especially for chatty APIs.
  • The downside is memory: an object per modification. A transaction like clone() cuts it to an object per batch, and Object.freeze() enforces immutability at a cost paid at creation.