Functional Fundamentals: Pure Function

This is the first part of a series covering some topics from functional programming.

What's functional programming? You can read entire books to answer that question, but I will just say that it is a programming paradigm in which a program is constructed with a series of simple, pure functions.

This is contrasted with the imperative paradigm, in which you probably learn to program, where you write a series of instructions and conditional branches.

Whether you learn functional programming or not is another question, but you will see many of these concepts around the web (and in more and more frameworks) so you should understand what they mean.

What's a pure function?

A pure function is a function that does not modify any part of your program other than its parameters.

For example:

function createThing(name) {
	var thing = {}; = name;
    return thing;

This function makes use of its parameter, but does not touch anything outside the function itself.

Contrast this with an impure version of this function:

var myThings = [];
function createThing(name) {
	var thing = {}; = name;

Even though this is valid code, the function is changing something beyond its responsibility. This is called a side-effect.

So what?

Even if you have no desire to become a functional programmer, writing as many of your functions as possible in a pure way only has benefits for you and others that may read/use your code.

Pure functions make your code easier to understand. If you write your functions in a pure way, then when another programmer or a much later you reads the code, they will be able to easily predict what will happen in the program just by reading the function names. If there are side effects within your functions, it may be difficult to debug, refactor or understand the order in which things are happening.

Pure functions are easier to test. Including references to objects outside your functions makes them difficult to test because those objects may not be accessible in a test scenario. This is where mocking comes in. However, depending on what you need to mock, this can be quite complicated. Make it easy on yourself to write those unit tests.