What Are Pure Functions?

In functional programming, functions should be pure, but what does that mean?

Pure functions only have explicit inputs and outputs

All functions have two sets of inputs and outputs, explicit and implicit. Here's an example of what I'm talking about:

function get_ship_by_drive(drive_type) {  
    return starships.filter((starship) => 
        starship.propulsion === drive_type)
}

This function has one explicit input and one explicit output, namely drive_type and a filtered list, but it also has an implicit input: starships.

The problem with writing code like this is that it becomes too tightly coupled with the surrounding state. You can no longer think about this function in isolation. Now we have to worry about starships and whether or nor anything else is messing around with it.

There is a similar problem with implicit outputs:

function add_ship(ship) {  
    starships.push(ship)
}

This function is effectively returning a modified list of starships, but when code like this is implicit instead of explicit, it becomes hard to track down where this modification occurs.

Sure, you can the see modification now that I'm showing it to you, but will you remember where it is when you're modifying code 6 months from now?

I have definitely had the experience, while trying to fix a bug, of nearly tearing my hair out just trying to find out when and where data is getting modified. When this kind of thing is implicit, it's hidden and hard to find.

Speaking of modification, here's the other defining characteristic of pure functions:

Pure functions don't have side effects

A side effect is anything a function does besides return a value.

Here's a function with a side effect:

function set_phaser_to_stun(phaser) {  
    phaser.change_setting('stun')
}

This is a similar example to add_ship, setting a phaser to stun is a side effect.

Here's another example:

var dog = {  
    bark: () => console.log('woof')
}

dog.bark does two things. It prints 'woof' to the screen and it returns undefined. Printing 'woof' is a side effect.

So wait, how do you get your program to do anything useful if you only use pure functions?

After all, pure functions can't query or update a database, get user input, or print to the screen.

The answer is that if your program only has pure functions, it won't be useful to anybody. The point is not to eliminate side effects, or even implicit inputs and outputs, but to only use them when you can't avoid it.

You might be surprised, however, to learn just how infrequently you need to use impure functions.

Looking for a software developer?