7 October 2017
Caution: side effects may occur
Side effects quietly break analysis, reuse, testing, typing, interactive development — and both fundamental ways of building software. Why that happens, and why the fix has to be fundamental too.
One should start with what sows doubt.
— the Strugatsky brothers
Typical frontend
Let’s look at a simple piece of frontend code:
var URL = 'https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cats'
function app() {
document.addEventListener('click', (event) => {
if (event.target.tagName === 'BUTTON') {
fetch(URL)
.then((response) => response.json())
.then((json) => json.data.image_url)
.then((gifSrc) => document.querySelector('img').setAttribute('src', gifSrc))
}
})
}
What is the result of this function?
- it makes an HTTP request with
fetch; - it sets the
srcattribute of animgtag with.setAttribute.
What does this function depend on?
- events received through
document.addEventListener; - the result of the HTTP request returned by
fetch.
Now let’s hide the implementation and look at the function again:
function app() {
...
return
}
Hmm, now it looks like the function depends on nothing and does nothing at all. Which is fair enough: without seeing the implementation we can’t tell what it does. Let’s look at another function:
function sum(list) {
var result = list.reduce((acc, item) => acc + item, 0)
return result
}
And hide its implementation too:
function sum(list) {
...
return result
}
In this case we can see both what the function depends on and what it returns: it clearly does something and returns a result computed from the list passed to it.
Why the difference? What distinguishes app from sum? What are these two different kinds of functions?
Two kinds of functions
sum takes its inputs only from its list of arguments and returns its result only via the return statement — in other words, it interacts with the surrounding code only through the standard mechanics of calling a function.
Such functions are called pure.
app, on the contrary, uses data that reaches it implicitly (not through its arguments) and delivers the result of its work implicitly (not through return).
Such functions are said to have side effects, and, as opposed to pure functions, they’re called impure.
So:
Side effects are a function's implicit dependencies, or the implicit results of its work.
Sounds simple enough, but in practice, in languages without explicit restrictions on purity, this definition turns out to be less clear-cut.
To avoid sophistry, instead of trying to define side effects, let’s try to identify their key properties. Whatever satisfies these properties is what we’ll consider a side effect.
Side effect — what are you?
First and foremost:
A side effect is not a first-class object
What does that mean? A first-class object is an entity in a programming language that:
- can be stored in a variable or a data structure;
- can be passed to a function as an argument;
- can be returned from a function as its result.
Put simply, a first-class object can easily be represented as a value. Obviously, that’s not true for side effects. We can’t just take app and rewrite it as:
function app(httpResponse, domEvent) {
... our logic
return { httpRequest, domMutation }
}

Side effects depend on, and affect, the outside environment
A fairly obvious property. To perform a side effect correctly, we need a suitable environment: an HTTP request needs a working network, a DOM query needs a constructed DOM, and so on.
Side effects deprive functions of referential transparency
Referential transparency is the property of a function that lets you always, anywhere, substitute a call to the function for its result.
That is, instead of var result = sum(list); return [result, result]; you can safely write return [sum(list), sum(list)];.
Functions with side effects don’t have this property: call app twice and you get completely different results (two listeners instead of one, two HTTP requests per click instead of one, and so on).
Side effects change the properties of the code that uses them — all the way up the call stack
A function with a side effect inside it becomes, in a sense, a side effect itself. What is fetch? A function that contains side effects, or a side effect as a whole? What if we wrap it in another function? What matters to us is that using side effects inside other functions makes those functions acquire all the properties of side effects.
In fact, the last two properties probably follow from the first — but that’s just a hunch, so I listed them separately.
What does all this mean for us?
Okay, so side effects have some specific properties. But what do those properties mean for us in practice?
Code with side effects is hard to analyse (for humans and machines alike)
First, let’s look at code without side effects — all the functions in it are pure.
function calcAnything(value) {
var a = calcA(value)
var b = calcB(value)
return calcC(value, b)
}
We can easily see which values depend on which, and which don’t matter. For example, we can see that nothing depends on a, so its computation can safely be removed.
function calcAnything(value) {
return calcC(value, calcB(value))
}
What’s more, we can draw the computation graph:
Now let’s try the same with code that may contain side effects:
function doSomething(value) {
var a = doSomethingA(value)
var b = doSomethingB(value)
return doSomethingC(value, b)
}
We can still say that, for example, b depends on value, but we can’t say with any certainty that b doesn’t depend on the computation of a. Imagine that doSomethingA writes something to a file that doSomethingB then reads. So in code with side effects any computation can potentially depend on any other, because they all affect the same outside world.
This affects:
- machine analysis (the IDE can’t tell us whether we’re using a function correctly);
- human analysis (code review often simply doesn’t work, because a change in one place affects another part of the system).
Refactoring also becomes much harder with side effects. For example, removing unused code:

Code with side effects is hard to reuse
This is a less obvious consequence. Let’s look again at code made of pure functions.
We’ve written a function that computes the length and the sum of an array:
function calcLengthAndSum() { ... }
Using it, we can easily write a function that computes only the length of a list:
function calcLength(list) {
return calcLengthAndSum(list).length
}
Or its mean:
function calcMean(list) {
var res = calcLengthAndSum(list)
return res.sum / res.length
}
Pure functions are extremely easy to reuse: even if they do something extra or something slightly wrong, we can always fix that by wrapping them in yet another pure function.
As the saying goes:
Any problem can be solved by adding another level of abstraction — except the problem of too many levels of abstraction.
Now let’s look at a function with side effects that makes an HTTP request and writes the result to a file:
function sendRequestAndWriteFile() { ... }
Now somewhere in the code we need to send the same request, but not write it to the file.
Most likely, we’ll add a special option to sendRequestAndWriteFile:
function sendRequest() {
return sendRequestAndWriteFile({
onlyRequest: true,
})
}
Same thing when we want to send requests to a different URL:
function sendRequestAndWriteFileOnUrl(url) {
return sendRequestAndWriteFile({ url: url })
}
Since a side effect is an implicit result, we can’t influence it outside the place where it’s created — we can’t drop part of it or transform it, as we could with the result of calcLengthAndSum.
This forces us to add lots of options to a function instead of simply reusing it, which greatly increases the code’s cyclomatic complexity (a.k.a. ESLint’s complexity).
The number of execution paths grows as 2ⁿ: a function with just two boolean options already has 4 execution variants, with three options — 8, and so on.
Side effects are hard to test
Everyone is probably familiar with this one. Compare:
it('2 + 2 = 4', () => {
var result = add(2, 2)
expect(result).toBe(4)
})
with:
it('remoteAdd send args to endpoint', () => {
var fakeRes = {}
mock(HttpClient, {
post: (...args) => {
return fakeRes
},
})
var result = remoteAdd(2, 2)
expect(result).toBe(fakeRes)
})
Looks a bit more complicated, right? But hold on — we haven’t checked that our function makes exactly one HTTP request. Let’s fix that:
it('remoteAdd send args to endpoint', () => {
+ var postCalls = [];
var fakeRes = {};
mock(HttpClient, {post: (...args) => {
+ postCalls.push(args);
return fakeRes;
}})
var result = remoteAdd(2, 2);
+ expect(postCalls.length).toBe(1);
+ expect(postCalls[0]).toEqual({url: URL, params: {a: 2, b: 2}});
expect(result).toBe(fakeRes);
});
Why do we write automated tests at all? To keep changes to the codebase under control. If the behaviour of the code changes, we immediately see the old tests fail. In a large enough codebase, different changes can conflict with each other and “break” one another. Automated tests protect our changes from being broken accidentally by some edit (even something as mundane as resolving a merge conflict).
Let’s change the functions under test and see what happens in each case:
function add(a, b) {
- return a + b;
+ return {result: a + b};
}
The test fails, of course — 4 is not equal to {result: 4}.
Now let’s change remoteAdd:
function remoteAdd(a, b) {
+ writeFile('log', [a, b]);
return HttpClient.post(a, b);
}
The function’s result has changed — now it also writes to a file. But our test didn’t notice at all and keeps passing as if nothing happened.

Since functions with side effects depend on and affect the outside world implicitly, to test such a function correctly we would have to:
- model the entire surrounding world (network requests, DOM state, file-system state) as some value before calling the function;
- call the function;
- check the state of the value that models the entire outside world.
Clearly, doing this completely correctly is most likely impossible, because the number of kinds of side effects in JS is unbounded.
The situation can be improved a little by a convention: every dependency that can perform side effects must be passed into the function explicitly:
-function remoteAdd(a, b) {
+function remoteAdd(a, b, HttpClient) {
return HttpClient.post(a, b);
}
Let’s add writeFile:
-function remoteAdd(a, b, HttpClient) {
+function remoteAdd(a, b, HttpClient, writeFile) {
+ writeFile('log', [a, b]);
return HttpClient.post(a, b);
}
Our test now fails with undefined is not a function, because we didn’t pass writeFile. Great!
What are the problems with this approach?
- we can’t tell precisely which dependencies perform side effects and which don’t, so we’ll pass absolutely all dependencies this way. Doing that by hand is obviously impossible, so we’ll need a special module system. This approach is called Dependency Injection.
- even with such a system we can still write a bad mock — for example, be too lazy to check calls to
HttpClient.put. Yes, we’ve made the dependency on the outside world more explicit. But we still have no standard way to compare the state of the world before and after, the way we can compare data with a standard deep-equality check. We’ll have to write that comparison again and again for each dependency and probably for each test. And sooner or later we’ll most likely make a mistake somewhere.
If we wanted to test code with side effects “honestly”, we’d have to write something like this:
// some object that tracks the state of the outside world
var world = new World()
var result = remoteAdd(world, a, b)
expect(result).toEqual(output)
// all changes to the outside world since the object was created
expect(world.changes()).toEqual(sideEffects)
Then we could compare the side effects a function performed with the expected ones using a standard .toEqual (plain deep object comparison). Simply passing dependencies through arguments (and DI as a consequence) doesn’t give us that — it’s a half-measure. On one hand it doesn’t fully solve the testing problem; on the other it adds complexity to our code: on top of the static module system there’s now a second, dynamic one. That happened because instead of eliminating the cause of the problem (the presence of side effects) we only tried to treat its consequences (difficulty of testing).
A more detailed article on why mocks are hard.
An alternative is to write fully integrated tests with a complete browser or server environment. On top of the same problems with creating and comparing environment state (how do you compare the whole DOM before and after an operation?), these add new ones:
- such tests are slow to start, slow to run, burn a lot of electricity and are unreliable;
- there’s no way to localise a problem: something doesn’t work, but why is unclear.
Side effects are unpredictable and irreproducible
Everything flows, everything changes; no one can step into the same river twice.
— Heraclitus
Would you wrap a call to add(2, 2) in a try/catch block? I don’t think so — there’s no point. What about divide(a, b)? Yes, of course — with b === 0 there will be an error.
Can calling remoteAdd(2, 2) throw, and if so, with which arguments? Yes, it can — with any arguments. Or it may not. We don’t know and can’t influence it. The outside world is unpredictable and can break at any moment: the browser can crash, the network can go down, the server can burn.
Because the outside world is unpredictable and constantly changing, we also can’t reproduce the results of computations that contain side effects.
add(a, b) === add(a, b) is always true, under any conditions and in any environment. We can easily reproduce a production issue by, say, taking the input data from monitoring and running the computation with those parameters. Side effects lead to irreproducible bugs: to understand what went wrong we have to analyse not only our code but the state of the entire surrounding world at that moment. That’s far more laborious, and sometimes outright impossible.
Side effects can’t be typed

One way to keep a codebase under control and prove the absence of undesired behaviour is static typing.
A lot of lances have been broken over whether it’s needed at all or not.
My view is simple: static typing is an indispensable tool for a certain kind of software — the kind with lots of code, lots of programmers and lots of interconnected subsystems.
But the question here is different: how do side effects affect the use of types? Suppose we have a function that modifies the DOM according to a description of the change:
function patchDOM(patch: DOMPatch): void { ... }
Implicitly, this function depends on the existence of the DOM, and its result is a change to it. Yet we can’t express any of this in the types — neither the implicit dependency on the DOM nor the fact that its result is a change to it. As a result, if we accidentally use this function in an environment without a DOM, we get a run-time error:
function serverProgram() {
...
patchDOM(patch) // run-time error
}
Because they’re implicit, side effects can’t be described by types, and the type checker can’t help us find problems with them.
One possible solution is to use emulated higher-kinded types to implement an Eff type in Flow:
type DOM = { type: 'DOM' }
function patchDOM(patch: DOMPatch): Eff<{ write: DOM }, void> { ... }
Then serverProgram simply won’t compile if its type doesn’t include an Eff of { write: DOM } while it uses patchDOM inside.
However:
- this approach relies on not-so-obvious
Flowmechanics and is rather hard to understand; - it doesn’t help with side effects in callbacks or other places you can’t return a result from;
- such types won’t be inferred for JavaScript APIs (
console,XMLHttpRequestand so on).
All in all, the solution is neither general nor simple.
Interactive development gets harder with side effects
Interactive development is gaining popularity. Practically every reasonably popular language ships a REPL (standalone or as part of the debugger). Modern browsers even let you write code right inside them.
Dedicated IDEs aimed at interactive development are appearing too — for example, Light Table, which lets you watch the results of computations in real time:

A great article on why interactive development is wonderful.
Let’s see how side effects affect this practice. Say we’re developing a function that sends a request to delete a user — deleteUser. Obviously, we can’t run it several times for the same user to check how it works in the REPL. What’s more, to check the result we’ll have to look at the current state of the server every time.
The main advantage of interactive development — fast feedback from the code you’ve just written — is cancelled out by the need to constantly watch the state of the outside world and periodically fix it up. For example, restoring the deleted user.
A possible solution here is a REPL integrated with a test framework — jest-repl, mocha debug REPL — with built-in support for mocking certain side effects.
Property-based testing is hard to apply to code with side effects
Property-based testing, or generative testing, is a technique that lets you describe properties of some program entity (a function, say) and check them by generating input values.
It’s a very powerful technique that lets you prove (with some degree of probability, of course) certain claims about code. It becomes especially important in languages without a strong static type system.
But, as I noted in my previous article, it’s extremely hard to define any property for code with side effects — because of their unpredictability.
Small pests doing big damage

Side effects are like gremlins: they break every tool available to a programmer that they can get their hands on — types, tests, interactive environments, static analysis in the IDE, code review.
But why does all this really matter? Well, some things got harder — but programmers are used to fighting complexity. And in each section above I mentioned the results of that fight: tools meant to reduce the negative impact of side effects at least somewhat.
The problem is that side effects don’t just make writing and working with code harder — they “break” the two fundamental ways of developing software. And that’s a real problem.
Two broken ways of developing software
At the very highest level, there are essentially only two ways of developing software. Everything else is either a combination of them or derived from them.

Let’s look at both on a simple example. Suppose we need to build a printSum system that prints the sum of some list to the screen.
Top-down
We define the specification of the top-level API — describing its input and output:
printSum(list: Array): PrintedSumToScreenEffect
Then we define the specifications of the next level down, which we need to get from Array to PrintedSumToScreenEffect. Clearly, we need two functions:
sum(list: Array): number
printToScreen(value: number): PrintedSumToScreenEffect
Now, just by looking at the specifications, we understand that first we need to call sum on list, and then printToScreen on its result.
What remains is to decide how to write specifications describing inputs and outputs:
- Ideally, a specification should describe all possible inputs and results in a fairly general way. Tests aren’t a great fit, since they describe individual cases rather than the general behaviour of the system.
- We must be able to check that the program we’ve built conforms to the original specification; otherwise there’s a big chance the implementation will drift significantly from it. Diagrams and other visual-arts methods won’t give us that.
You’ve probably guessed that the best fit here is a good type system.
People sometimes ask me: “What’s the equivalent of UML for Haskell?” When I was first asked that, ten years ago, I thought: “I have no idea. Maybe we should invent our own UML.” Now I think: “It’s just types!” People draw UML diagrams to understand the overall structure of a program. That’s exactly what programmers in functional languages, in Haskell, do when they come up with type signatures for modules and for the functions in them.
— Simon Peyton Jones (retranslated from a Russian interview)
However, as we’ve found, without certain tricks most type systems can’t deal with side effects, and they certainly can’t infer the types of such effects from context. We could, of course, replace types with tests (as is done, for example, in the well-known Test-Driven Development), but as we’ve seen, tests aren’t a great fit because of their discrete nature — and they suffer from side effects too.
So side effects break the first fundamental way of developing software. Maybe we’ll have better luck with the second?
Bottom-up
We can come from the other side.
From the description of the task alone it’s clear that we’ll need to be able to print something to the screen and to add numbers. We won’t try to define precise specifications. Instead we’ll just write general, minimal functions for that. These functions will most resemble small, separate libraries (very general and very reusable units), since we don’t yet know what API we’ll have to build with them.
sum(1, 2, 3, 4)
// -> 10
print('Hello', screen)
// -> prints 'Hello' to screen
Then we build a higher-level API out of these functions:
function printSum(list) {
print(sum(...list), screen)
}
For an iterative process like this we need a tool that makes it easy to experiment with small pieces of code and to quickly run individual functions on different inputs. During development it’s not that important to pin down a result and be able to reproduce it — most likely we’ll rarely change the implementation of an API we’ve already written. Tests would rather get in the way here, with their slow feedback and their fragility.
The best fit for this style of development is a REPL. In fact, this style became widespread precisely in languages with a rich REPL culture: Lisp, Smalltalk.
But, as we remember, the REPL loses its main advantage (fast feedback) when developing code with side effects. The second fundamental way didn’t survive this battle either.

But not all of our code contains side effects, does it? Maybe all these troubles only concern the places where we use them? Maybe we should just try to use fewer “impure” functions and more “pure” ones?
Ice-nine for source code

— Have you read Cat’s Cradle?
— No.
— Well, in that novel the world ends because a molecule is discovered in ice that turns any water it touches into ice. And since all the waters of the world are connected — the pond with the stream, the stream with the river, the river with the lake, the lake with the ocean — the whole world freezes and dies. And that molecule is called “ice-nine”.
Programmers who remember JS before Promise and async/await may find something familiar in this list of the drawbacks of side effects. The same problems were often brought up in discussions of callback-based asynchronous functions.
Asynchrony and side effects look like closely related problems: solve only one of them and you won’t get rid of all their drawbacks — they’ll just move elsewhere. On the other hand, a good solution to one of these problems can help solve the other. We’ll see later that this isn’t a coincidence: both phenomena are just special cases of a more fundamental problem — the lack of a general way to abstract a program’s control flow and express it with first-class values.
But the worst thing about such functions was that they infected all the code that used them. An ordinary function that used a callback-based function stopped returning its result via return and started passing it to a callback — and in turn became “poison” for the code that used it.
There’s even a metaphor for this — the two-colour language:
- Bob Nystrom’s article
- Andrey Salomatin’s talk (in Russian)
blue•function doSomethingAzure() {
// This is a blue function...
}
red•function doSomethingCarnelian() {
// This is a red function...
}
blue•function doSomethingAzure() {
doSomethingCarnelian()•red; // Error — you can't call red inside blue
}
All functions in the language are divided into “red” and “blue”. And to call a “red” function from a “blue” one, you have to repaint the “blue” function red.
This happened because such asynchronous functions didn’t use the standard way of interacting with code — returning a value via return. As we remember, functions with side effects behave the same way and return their results implicitly.
So everything above applies to them too:
A function with a side effect inside becomes a side effect itself. So by using such a function inside another (pure) one, we automatically make it impure — it starts returning part of its result implicitly. And so on, all the way to the top of the call stack.
Let’s look at an example. Suppose we have this hierarchy of calls:
All the calls are pure and predictable. No problems at all.
But suddenly we need to cache the results of calcForItem in localStorage:
function calcForItem(...) {
...
var cachedResult = localStorage.getItem(argsHash)
if (cachedResult) {
return cachedResult
} else {
...
localStorage.setItem(argsHash, res)
return res
}
}
And our hierarchy now looks like this (functions with side effects are marked red):
By changing the code of just one function, we changed the properties (testability, reliability, composability) of the entire call stack.
In a sense, we lose control over our code. Its behaviour can change even though the code itself stays the same — the API our code is built on just suddenly becomes “impure” and “infects” it.
In Soviet Russia, side effects control you!
If we don’t control the software, it starts controlling us (the developers). As a result of everything above, we end up with code that:
- can’t be fully tested, and even testing it somewhat takes a lot of effort — so we write too few tests. Compare your coverage of code with side effects and code that only works with data; most likely the second number is much higher;
- can’t be fully typed, because a significant part of frontend code consists of functions like
handleClick(): void,dispatch(): void,setState(): void; - can’t be verified, or have its properties checked with property-based tests — most of it simply has no predictable properties;
- is inconvenient to work with in an interactive environment (
REPL), because you can’t work with DOM elements there or safely send an HTTP request; - barely lends itself to refactoring, because side effects create implicit dependencies;
- is unpredictable — it’s impossible to build reliable tools for reproducing the application’s behaviour. Understanding what happened from monitoring data is usually not a problem. But why it happened can be completely unclear, because parts of the application affect each other implicitly;
- is very hard to reuse. Sometimes a solution can’t be reused without editing its source. So developers, taught by bitter experience, often avoid reusing large parts of their applications (let alone large and complex third-party components), because it’s unclear whether they’ll be able to get rid of unwanted behaviour if it suddenly becomes unnecessary.
And developers don’t want to write such code. Almost any developer will tell you code should be well tested, reusable, and so on. We’re taught this from the very beginning of our careers.
Yet side effects in our code force us to partially give up all those good practices and almost all the tools available to a programmer. Software that controls people? I know someone who’d love that:

And we don’t even try to escape this control — we take it for granted. All these problems have been known for a long time, but instead of addressing their cause, we only fix individual symptoms:
Reactbecame popular largely because it abstracted away part of the side effects involved in working with theDOM. But only part: handling events and working with individual elements still happen through side effects.Reduxlet us describe transformations of global mutable state with pure functions. But the changes themselves are triggered by the impuredispatchfunction. And, for example, networking still produces side effects (though this can be fixed withredux-looporredux-saga).Angular 2, on the contrary, lets you handle events without callbacks (that is, without side effects). But it has no solution for abstracting the remaining side effects.
I have a dream…
Trying to solve a fundamental problem by fighting only its individual manifestations is unlikely to succeed.
We need a fundamental solution to the problem of side effects in our code. And it should be as general as possible — not tied to any framework or infrastructure, and not imposing any particular architecture. It should solve exactly one problem, and solve it well.
But how can we build such a solution?
We can’t get rid of side effects entirely, or even reduce their number — we can’t suddenly start making fewer HTTP requests or working less with the DOM. Side effects — interaction with the outside world — are actually the most important part of our application. If an application doesn’t perform them, it most likely doesn’t do anything at all.

But we can completely separate the logic of our application from its side effects.
Our whole application becomes a pure function: it explicitly takes all incoming effects and explicitly returns all outgoing ones. And the side effects are executed separately from the main application.
There are at least three ways to do this, and all of them rest on theoretical foundations of computer science laid down about 40 years ago.
What unites them is that they were created to abstract a program’s control flow. Control flow is the skeleton of our program, its basis — which is why these approaches show up when solving most problems in computer science, not only the problem of side effects. But that’s a topic for the next article — and for the talk.