Skip to content

Functional Styles in Everyday Code

Why functional style in everyday team work in 2015 does not mean Haskell, but the discipline of separating pure functions from I/O – and how ES2015 finally makes that convenient.

≈ 11 min readSoftwareArchitecture

Functional Styles in Everyday Code

When business logic and side effects sit unseparated in the same function body, there is a very concrete consequence: every test needs a database. If you want to check whether an invoice counts as overdue, you first have to load test data, replace a mailer with a stand-in and clean everything up afterwards. The test suite runs for minutes instead of seconds, so it runs less often, so nobody dares to touch exactly the places that most urgently need a change. That is not a tooling problem and not a framework problem – it is a style problem.

Many colleagues still regard functional programming as an academic affair: Haskell, monads, type theory. What I mean by it in everyday project work is much more modest and at the same time more effective: pure functions as the standard building block, data flow instead of state mutation, map/filter/reduce instead of loop bodies with side effects. No new language, no new runtime – a discipline in the language that is already in use.

Pure functions as the standard building block#

A pure function is quickly explained: same input, same output, no observable side effect. It does not read the clock, does not write to the database, does not change any variables outside its body. That sounds trivial, but in code that has grown over time it is the exception. More typical is a function that loads data, filters it, converts it, saves it and sends an email on the side – five responsibilities in thirty lines.

At the beginning of the year, I forked Crista Lopes’ collection exercises-in-programming-style: the same small task – a word frequency analysis – in dozens of programming styles, each style its own folder with program and description. While working through it, I noticed something that had not been that clear to me before: style is a decision, not a language feature. The same task can be written in Python monolithically, object-oriented or as a pipeline of pure functions. The language prevents none of it and enforces none of it. The same is true for JavaScript and C#.

The discipline lies in making the pure function the normal case. Not: “Where could I sprinkle in something functional?” but the other way around: every function is pure until there is a reason against it. And the reasons against it – I/O, time, randomness, DOM, database – then gather in a few named places instead of everywhere.

What ES2015 changes about this#

ECMAScript 2015 has been ratified since June – the specification is final, and Babel 5 already compiles the new standard down to ES5 today. Node 0.12 and io.js support parts of it natively; for the rest, the transpiler stays in the build. For the functional style this is more than cosmetics, because three new features lower exactly the writing costs this style used to founder on:

  • Arrow functions make small functions so cheap that you actually write them – x => x.amount instead of a four-line function block with return.
  • const documents in the code that a binding is not reassigned – the reading direction flips: mutation becomes the marked exception.
  • Destructuring takes data structures apart without helper variables, which is what makes functions over plain objects pleasant in the first place.

The transpiler is an honest extra cost item: the build gets one step longer, source maps have to be right, and if you debug in the browser, you occasionally look at generated ES5 code instead of what you wrote. In our case it was worth the trade – but it belongs on the table before the team agrees, not after.

Before, functional style in JavaScript was possible but syntactically expensive. A function (invoice) { return !invoice.paid; } at every filter call is tiring, and what is tiring does not get done. With arrow functions the balance tips: the compact form is now also the disciplined form. In an ongoing project, I saw how the switch to Babel alone multiplied the number of small helper functions in the team – not because anyone ordered it, but because it was suddenly the most convenient way.

From loop body to data pipeline#

The difference becomes concrete in a piece of code like the one found in every back-office system: from a list of invoices, find the overdue ones, create reminders and calculate the open amount. The common form looks like this:

function processInvoices(invoices, db, mailer) {
  let total = 0;
  for (let i = 0; i < invoices.length; i++) {
    const invoice = invoices[i];
    if (!invoice.paid && invoice.dueDate < Date.now()) {
      total += invoice.amount;
      db.markAsOverdue(invoice.id);
      mailer.sendReminder(invoice.customerEmail, invoice.amount);
    }
  }
  return total;
}

The code works, and that is exactly what makes it long-lived – nobody touches a function that has been quietly doing its job for two years. Still, the loop body mixes four things: the business rule (when is an invoice overdue?), the aggregation (sum), the database access and the mail delivery. On top of that, the function secretly reads the clock with Date.now() – the same call returns a different result at midnight than at 23:59. It can only be tested with a real database, a real mailer replacement and frozen time.

The same logic as a data flow, with ES2015:

const isOverdue = (today) => (invoice) =>
  !invoice.paid && invoice.dueDate < today;

const toReminder = (invoice) => ({
  invoiceId: invoice.id,
  email: invoice.customerEmail,
  amount: invoice.amount
});

const totalAmount = (invoices) =>
  invoices.reduce((sum, { amount }) => sum + amount, 0);

const overdueReminders = (today, invoices) => {
  const overdue = invoices.filter(isOverdue(today));
  return {
    reminders: overdue.map(toReminder),
    total: totalAmount(overdue)
  };
};

Four pure functions. Time comes in as a parameter instead of from the clock, the business rule stands isolated in isOverdue, and overdueReminders only describes what should become of the data – not how a loop variable gets incremented. The test for it is an array literal and an equality check, no database anywhere in sight. And whoever reads the code in half a year sees the rule at a glance instead of dissecting it out of a loop body.

The impure edge#

The honest limit belongs here too: db.markAsOverdue and mailer.sendReminder have not disappeared. I/O, DOM and database stay impure – an application that reads nothing and writes nothing is useless. The point is not to forbid side effects, but to push them to the edge, where they are visible and thin.

flowchart LR
  DB[(Database)] -->|load invoices| Edge[Impure edge<br/>I/O, clock, mailer]
  Edge -->|data in| Core[Pure core<br/>isOverdue, toReminder,<br/>totalAmount]
  Core -->|result out| Edge
  Edge -->|send reminders| Mail[Mail server]

At the edge, the code then looks like this – with ES2015, promises are part of the language:

const today = Date.now();

db.loadInvoices()
  .then((invoices) => overdueReminders(today, invoices))
  .then(({ reminders, total }) => {
    reminders.forEach((reminder) => mailer.sendReminder(reminder));
    log.info(`sent ${reminders.length} reminders, open amount: ${total}`);
  });

This edge is deliberately boring: load, call the pure function, write the result away. It is hardly ever tested on its own because it contains hardly any logic – the logic lives in the core, and the core knows neither database nor mailer. In one project, after exactly this split, we cut the integration tests down from half an hour to a handful of edge cases; everything domain-related ran as a plain unit test in seconds.

The view from the .NET world#

If this looks like a JavaScript fad to you, a look at the .NET world, where I also come from, helps. There, the same idea has been called LINQ for years and no longer upsets anyone:

var overdue = invoices
    .Where(invoice => !invoice.Paid && invoice.DueDate < today)
    .ToList();

var reminders = overdue.Select(invoice => new Reminder
{
    InvoiceId = invoice.Id,
    Email = invoice.CustomerEmail,
    Amount = invoice.Amount
});

var total = overdue.Sum(invoice => invoice.Amount);

Where, Select, Sum – those are filter, map and a specialized reduce. In C# teams, everyone has been writing this for years without calling it functional programming; it is simply the normal way to work with collections. If you bring a foreach loop with a running total into a review there, you get asked why it is not LINQ. This observation takes the ideology out of the topic: it is not about a camp, but about a form of expression that established itself long ago in a very pragmatic environment – JavaScript is catching up with ES2015 right now.

Underscore, Lodash, Ramda#

For the gaps in the standard library, there are toolboxes. Underscore was the default for years, and Lodash has practically replaced it with version 3 – same idea, more functions, and since Lodash 3 chained calls are evaluated lazily, so long chains do not have to create an intermediate array at every step. Ramda has gone one step further for a good year now: all functions are automatically curried, and the data comes as the last argument, so processing steps can be plugged together into new functions:

const openAmountOf = R.pipe(
  R.filter(isOverdue(today)),
  R.map(R.prop('amount')),
  R.sum
);

const total = openAmountOf(invoices);

openAmountOf is a named, reusable pipeline – not a call but a definition. That is elegant, and this is exactly where the friction begins.

Where it chafes in the team#

The functional style has real costs in everyday team work, and if you keep quiet about them, you rightly lose the skeptics. Three points come up for me regularly:

  • Debugging chains is more tedious than debugging a loop. In a for body you set a breakpoint and see all local variables; in a pipe chain of anonymous functions, the stack trace shows cryptic names, and to look at intermediate values you have to break up the chain or insert a tap function.
  • Point-free style quickly tips over into an end in itself. A trained eye reads R.pipe(R.filter(...), R.map(R.prop('amount')), R.sum) fluently – three more levels of composition later nobody can read it anymore, not even the author. In reviews, one simple question has proven itself for us: can the colleague at the next desk read the line aloud without explanation and say what it does?
  • The performance argument comes reliably and is mostly a myth. Yes, filter and map create intermediate arrays, and a hand-written loop is faster on a million elements. But very few places in the code process a million elements – they process thirty invoices, and the real bottleneck is the database call next to them. Measure first, then optimize; the two hot paths that are really affected can happily stay a commented loop.

There is also a social component: a team in which two people love Ramda and five cannot read it has gained nothing from the style. The common denominator – map, filter, reduce, pure functions, a thin edge – carries further than perfect composition. The library is negotiable, the discipline is not.

Outlook: streams#

Once you have internalized the separation of core and edge, you find the next step almost by yourself. RxJS treats events – clicks, WebSocket messages, timers – as collections over time, with the same vocabulary: map, filter, reduce or scan on streams instead of arrays. The pure functions from the core can be used unchanged; only the impure edge then speaks observables instead of promises. For UIs with many concurrent event sources that is a noticeable gain – but that is a separate article.

The bottom line#

To me, functional programming in the everyday work of 2015 does not mean switching languages or putting category theory on the team. It means cultivating three habits: functions are pure until there is a reason against it. Data flows through map, filter and reduce instead of being mutated in loop bodies. And everything impure – clock, database, DOM, network – is gathered at a thin, boring edge. ES2015 makes these habits truly convenient for the first time, LINQ has shown for years that they are fit for the mainstream, and the test suite thanks you right away: the part of the system where bugs hurt suddenly no longer needs a database. Nobody has to learn Haskell for that – you just have to stay consistent when the next loop with a running total shows up in a review.

Further reading#

Revised and translated from German with the help of AI.