3 reasons why fluent APIs matter

- select the contributor at the end of the page -

You can’t write much code (especially in C#) without encountering a fluent API. Not sure what that is? Well, if you’ve seen a sequence of chained function calls, often arranged in a way that reads like an English sentence, then that’s a fluent API:

  someObject.ShouldNotifyFor(x => x.FirstName)
     .And(x => x.FullName)
     .When(x => x.FirstName = "Floyd");

Let’s look at three reasons why fluent APIs are worth considering.

1. Readability is a primary design concern

Let’s take a journey back in time. It’s 1984. Object-oriented programming had yet to gain traction, personal computers were still a bit of a novelty and mainframe programming was still common. Many programmers still used punched cards. Yikes. Computer programming technology was primarily driven by what was easiest for the computer. In this illustrious year, Professor Donald Knuth — one of the founding fathers of computer science — published a book titled “Literate Programming” at the University of Stanford. Knuth espoused the idea that a program should be written like an essay: an expository text whose target audience is a human reader. Knuth intended computer programs to be written like prose.

Less than two years later, MIT professors Harold Abelson, Gerald Jay Sussman, and Julie Sussman co-authored the book “Structure and Interpretation of Computer Programs.” The preface of this book contains a very interesting quote:

“…programs must be written for people to read, and only incidentally for machines to execute.”

Call it coincidence, but these two books appeared on opposite coasts of the USA at almost the same time. This strikes me as something beyond mere coincidence. Both books were written at well-regarded universities. Both were authored by highly-regarded professors. They both touted that the “how” and the “why” of a program must be woven together for the benefit of the parsing algorithms executing on a wrinkled wad of protein between someone’s ears. Imagine what impact Knuth, Abelson, and Sussman’s ideas might have on a programmer who used punched cards every day.

We benefit today from these professors’ revolutionary concepts. Contemporary programming languages and tools are designed for the benefit of the humans rather than the computer. We enjoy having powerful and user-friendly abstractions at the ready with just a few keystrokes. With that power, however, we must remain vigilant. The inevitable truth of software development is that code is written, and then it’s changed. The risk of that change is always magnified when the intent of the code is obscured because it is too obtuse or too cryptic for its purpose to be clear. Unintended consequences abound when we are forced to modify code that we don’t fully understand.

We have to embrace techniques that make code easier to read and understand, because the cost of those unintended consequences can be astronomical. 

2. Fluent APIs emphasize the purpose of your code

Consider the following two code samples that filter and sort a collection of vehicle objects. Both accomplish the same thing, but in very different ways:

   .Where(x => x.Wheels > 2)
   .OrderBy(x => x.Make)
   .ThenBy(x => x.Model)

This example makes use of LINQ, a fluent API, to sort and filter a collection of vehicles. The next example forgoes the use of LINQ:

  var outputVehicles = new List();

foreach(var vehicle in vehicles)
    if(vehicle.Wheels > 2)
outputVehicles.Add(); } outputVehicles.Sort(new VehicleComparer());

class VehicleComparer : IComparer
    public int Compare(Vehicle x, Vehicle y)
      var val = x.Make.CompareTo(y.Make);
      if(val != 0)
        return val;

      return x.Model.CompareTo(y.Model);

It’s quite interesting that the fluent API allows us to express the very same concept in just 5 lines of code, rather than the 22 lines to express otherwise. In the longer example, the effect that the code has on the output collection is obscured by the sheer bulk of the code. The intent is hidden in the longer code sample among a bunch of tedious boilerplate. In the first sample, the intent is front-and-center. In the second example, the code just seems to say, “Blah, blah, blah.”

Fluent APIs are fantastic tools for stripping away repetitive, verbose constructs that mask the code’s raison d’etre. In our example above, the details of how the filtering and sorting are done are hidden away, because what we’re filtering and sorting is more important.

3. Fluent APIs let you wield complex concepts with ease

Fluent APIs are a type of Domain Specific Language, crafted to solve a particular type of problem better than a general-purpose language, like C#, Python or JavaScript. These special-purpose dialects harness the features of the host language and couple them with intelligent names that allow you to write code that reads like English sentences.

There is an unparalleled creative power that fluent APIs facilitate. Programmers can use them to weave together clauses and phrases, much like an author or poet does. The clever intersection of language art and technical design enables coders to compose concepts in a way that clever object-oriented techniques alone cannot do. The expressive freedom that fluent APIs grant can be a productive way to express intricate ideas with clarity.

Learn more about designing fluent APIs in C# here

Get our content first. In your inbox.

Loading form...

If this message remains, it may be due to cookies being disabled or to an ad blocker.


Floyd May

Floyd is Tulsa's favorite cranky old software curmudgeon. He began programming at age nine drawing pictures with the Logo programming language, and has been in love with programming ever since. He frequently rants and raves at Tulsa area user groups and conferences, where he is well known as one of Tulsa's most passionate software craftsmanship advocates. Just be sure to stay off his lawn.