Pure functions

A pure function is a function that does not have a side-effect. Nothing the function does will ever affect a variable outside of it. This means that the input argument, when used in a computation, should not cause a side-effect, such as talking to the filesystem or opening a network connection, for example. Let's look at an example:

function notAPureFunction(filePath) {
const fileContent = fs.readFileSync(filePath);
const rows = fileContent.split(',');
let sum = 0;
rows.forEach(row => { sum += row; });
return sum;
}

As we can see, our function opens up a file, loops through its rows, and calculates a sum of all the row contents. Unfortunately, the function talks to the filesystem, which is considered a side-effect. It may look a little bit contrived, but in a longer function it is not an impossibility to see both calculations—logging and talking to a database—take place, or so has been my experience. Such code is far from ideal, and suffers from separation of concerns and a whole lot of other issues. When it comes to pure functions though, it is a good idea to isolate the pure parts into their own functions, which would result in this:

function calculateSum(rows) {  // now it's pure
let sum = 0;
rows.forEach(row => { sum += row; });
return sum;
}

function getRows(filePath) { // still not pure, but some things needs to perform side-effects
const fileContent = fs.readFileSync(filePath);
const rows = fileContent.split(',');
}

As you can see, we now have two functions. We managed to isolate the pure parts into a function called calculateSum() and we ended up creating the getRows() function, which performs side-effects. Most programs have side-effects in some form, but your job as a programmer is to keep those functions away from pure functions as much as possible.

In reality, we have described two things here:

  • Pure functions: They are more like mathematical computations that do not have side-effects.
  • Single responsibility principle (SRP): Part of doing functional programming well is writing small and focused functions. Even though this is not a strict property of functional programming or pure functions, it is an important principle that will help you have the right mindset while adopting the functional programming lifestyle.

One thing we didn't mention was why pure functions play an integral role in functional programming. They are predictable through their computational nature, which makes them easy to test. Building a system that mostly consists of many small predictable functions makes the whole system predictable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.173.40