Chapter 3. Pure Functions

We use functions to perform specific tasks and then combine them to build our applications. Each function is designed to do some work, given a set of inputs. When we don’t return the result of our execution but rather mutate another external (i.e., not contained within the function scope) object, we call this a side effect. Pure functions, on the other hand, are functions that have no side effects and always perform the same computation, resulting in the same output, given a set of inputs. Although most of this seems straightforward, the implementation is quite another story.

Functions performing large amounts of work are difficult to test. Generally, to allow for your code to grow over time, you need to be able to change functionality. This means the larger your function becomes, the more parameters you need in order to modify the functionality. You should break up the function into smaller functions. These smaller functions can then be pure, allowing for a better understanding of the code’s overall functionality. When a function is pure, we say that “output depends on input.”

Output Depends on Input

If we pass a set of parameters into a pure function, we will always get the same result. The return is solely dependent on the parameter list.

Don’t Closures Break Function Purity?

If we pass a closure, aren’t we then dependent on the external (closed-over) variable? This is an interesting point, so let’s think about closures and how they work. Closures work by ...

Get Becoming Functional now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.