OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

Forever Functional - Chaining Calls for Fluent Interfaces

Federico Kereki
June 25th, 2021 · 5 min read

Chaining calls is a way to design fluent interfaces, which in turn allow for clearer, more understandable code.

How do you design a clear API? More specifically, how can you make your API easier to use? The concept of a “fluent interface”, based on “chaining”, lets you provide a more streamlined development experience to developers. While in the two previous articles in this series (here and here) we looked at improving performance, now we’ll focus on improving clarity and usability.

What is Chaining?

Composing and pipelining are common patterns to apply a sequence of transformations when you work functionally . However, when you work with arrays or objects, there’s another way of linking those calls: by chaining them. A well known example of this is provided by map(...) or filter(...), each of which returns a new array, to which you can apply further calls. As a trivial (somewhat exaggerated!) example, let’s see some code from my Mastering JavaScript Functional Programming book. We can start by defining some essentially nonsensical operations:

1const testOdd = x => x % 2 === 1;
2const testUnderFifty = x => x < 50;
3const duplicate = x => x + x;
4const addThree = x => x + 3;

We can now apply those maps and filters, in sequence, to an array:

  • First, we’ll drop even numbers;
  • then, we’ll duplicate those that are left;
  • we’ll filter out results that are 50 or more;
  • and we’ll finish by adding 3 to whatever remains.
1const myArray = [22, 9, 60, 24, 11, 63];
2
3const a0 = myArray
4 .filter(testOdd)
5 .map(duplicate)
6 .filter(testUnderFifty)
7 .map(addThree);
8// [ 21, 25 ]

The .map(...) and .filter(...) operations return a new array, to which you can apply further operations. You could have done this in several lines as shown below, but (I hope) you’ll agree that this isn’t as clear. (A reader would wonder if x1, x2, and x3 would be used again, for example.) This is the alternative code:

1const x1 = myArray.filter(testOdd);
2const x2 = x1.map(duplicate);
3const x3 = x2.filter(testUnderFifty);
4const a0 = x3.map(addThree);
5// [ 21, 25 ]

So, chaining implies that operations will return some object to which you may apply further operations. This is interesting by itself, but it makes more sense in the context of “Fluent Interfaces”, which we’ll discuss below.

What are Fluent Interfaces?

What is a “fluent interface”? The term was invented by Martin Fowler back in 2005; the idea is chaining method calls, so code will be more legible, almost becoming a domain-specific language. A fluent API is primarily designed to be highly readable, using terms (methods) that are close to the domain you’re working on. This explanation may be hard to understand, I admit, so let’s see a couple of examples.

A well-known library that implements a fluent interface is jQuery. For example, you can write something like the following, that will access a DOM element, set some of its attributes, add CSS, and make the element visible, all in a single line.

1$("#titlephoto")
2 .attr({
3 alt: "Street scene",
4 title: "Pune, India",
5 })
6 .css("background-color", "black")
7 .show();

You could get the same result in several lines — but this is cleaner. Another example: the testing framework Jest applies fluent interfaces everywhere. For example, you can define a mock function that will return true once, then false, and undefined from that point on, in a single line.

1const fakeTest = jest
2 .fn()
3 .mockReturnValueOnce(true)
4 .mockReturnValueOnce(false)
5 .mockReturnValue(undefined);

Let’s go for a final example. The popular D3.js library also uses this style to join together several method calls.

1d3.select("svg")
2 .append("text")
3 .attr("font-size", "20px")
4 .attr("transform", "translate(100,0)")
5 .attr("x", 150)
6 .attr("y", 200)
7 .text("Sample Chart Title");

The key to the concept of a fluent interface is that it somehow mimics the way you think (“ok, select such element, append some text to it, change its font size, …”) making code more understandable. Chaining method calls is the way to achieve this, but don’t just think of it as a way to allow to write shorter code or avoid needing some extra intermediate variables. Conciseness and terseness are convenient, but not necessarily the best reasons for adopting the chaining pattern. Instead, consider chaining as a means to develop a Fluent Interface.

With this out of the way, let’s consider how we can implement this pattern by ourselves, for our own code.

DIY: Chaining method calls

How can we implement chainable methods? The first solution, doing it by hand, is possibly the simplest. We just have to modify each method to return this at the end — excepting, obviously, methods that need to return something else! This is certainly a solution, but we may think of something that needs less work, and proxy objects are a possibility.

A proxy object can intercept calls to another object, redefining how it works. You define a proxy by providing an object (the one whose methods will be intercepted) and a handler, that will implement whichever changes you want to achieve. Note that we won’t be able to “proxify” a class; we have to proxify each object by itself.

In our case, we’ll want to intercept all method calls, and make them return a reference to the object itself… unless, of course, the method is returning something else. This poses a slight problem: how do we detect if a method isn’t returning anything. JavaScript, by default, works as if a return undefined statement had been added to functions or methods that don’t otherwise return anything - so if your class has a method that may actually return undefined, we’re in trouble!

An implementation of this proxy may be as follows; the makeChainable(...) function will transform an object into a chainable alternative, all of whose methods (that don’t return undefined) will be returning a reference to the object itself.

1const makeChainable = (obj) =>
2 new Proxy(obj, {
3 get(target, property, receiver) { /* 1 */
4 return typeof target[property] === "function" /* 2 */
5 ? (...args) => { /* 3 */
6 const result = target[property](...args); /* 4 */
7 return result === undefined ? receiver : result; /* 5 */
8 }
9 : target[property]; /* 6 */
10 }
11 });

A handler provides multiple “traps” for different operations and types of access. We want to intercept “get” calls (1) that make target methods or attributes. If the target is a function (2) we’ll return a modified function that will accept the same arguments (3) as the original method, invoke that method (4), and then test if the result was undefined in which case it will return a reference to the proxied object (5) instead of the original returned value. If the target wasn’t a function, it was an access to an attribute; we return it (6).

Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder. OpenReplay is the only open-source alternative currently available.

OpenReplay

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

A gangland example

Let’s say we are developing an application with data on mobsters from the thirties — maybe we’re setting up a new “Untouchables” movie? We could have a class allowing us to record the first and last names of a criminal, as well as its nickname or alias.

1class Mobster {
2 constructor(firstName, lastName, nickname) {
3 this.firstName = firstName;
4 this.lastName = lastName;
5 this.nickname = nickname;
6 }
7
8 setFirstName(newFirst) {
9 this.firstName = newFirst;
10 }
11
12 setLastName(newLast) {
13 this.lastName = newLast;
14 }
15
16 setNickname(newNickname) {
17 this.nickname = newNickname;
18 }
19
20 getFullName() {
21 return `${this.firstName} "${this.nickname}" ${this.lastName}`;
22 }
23}

As is, objects in this class aren’t chainable. The three setters do not return this, so you cannot chain methods. Certainly, we could rewrite the class by adding some lines as follows… but we’ll look for a better, functional way of doing this.

1class Mobster {
2 constructor(...) { ... }
3
4 setFirstName(newFirst) {
5 this.firstName = newFirst;
6 return this; /* added */
7 }
8
9 setLastName(newLast) {
10 this.lastName = newLast;
11 return this; /* added */
12 }
13
14 setNickname(newNickname) {
15 this.nickname = newNickname;
16 return this; /* added */
17 }
18
19 getFullName() { ... }
20}

To simplify creating new chainable objects, we could write a helper or we’ll first have to create an object and then make it chainable; it’s better to do all this in a single step. The helper we need does those two steps at once.

1const makeMobster = (...args) => makeChainable(new Mobster(...args));

Now we can write code as follows.

1const gangster = makeMobster("Alphonse", "Capone", "Al");
2console.log(gangster.getFullName());
3// Alphonse "Al" Capone
4
5console.log(
6 gangster
7 .setFirstName("Benjamin")
8 .setLastName("Siegel")
9 .setNickname("Bugsy")
10 .getFullName()
11);
12// Benjamin "Bugsy" Siegel

Using chaining, you can design your code to be fluent, for more readable code — by changing how you create an object!

Summary

When designing an API of your own, going for a fluent interface produces a more easily used library. Chaining is key in implementing this pattern, and functional programming lets you transform any object into a chainable equivalent, instead of having to do it by hand. With this technique, your code will become simpler and more understandable; try it out!

More articles from OpenReplay Blog

3 Design Patterns in TypeScript for Frontend Developers

These are the 3 most common design patters in front-end development and you've been using them whether you knew about them or not

June 22nd, 2021 · 5 min read

React 18 Is Out! This Is What You Need to Know

React 18 has been announced, but what's new about it? Here are the details you need to know about this new version of React.

June 18th, 2021 · 7 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552