How we improved readability of our functional code

InventiStudio
2 min readOct 3, 2017

--

One of the most important rules for writing a deterministic, easy-to-debug code is avoiding side effects. The obvious choice if we want to meet this assumption is to use the functional paradigm. This, however, poseses a risk of poor code readability. This problem is especially evident in situations where we perform a series of transformations on the input data.

Let’s take a look at the available solutions and point out pros and cons of these.

1. Traditional assembly of functions, i.e. nesting of calls

Nesting calls known from math lessons is a solution that first comes to mind.

What we need to pay attention to right from the beginning is the reversed order of calls, which in real applications will result in a significant loss of readability of the code. Let’s take a look at a real life example.

or rather

2. Use of temporary variables / constants

The second approach is to use temporary variables storing the results of subsequent transformations.

In comparison to the first solution we got a series of calls from the top to the bottom, which is much clearer. Unfortunately, we’ve created a series of completely unnecessary constants, which we use only in one place (in the next transformation). Additionally, we fall into the trap of naming. Either we’ll come up with long and complex names for the next result’s data, or, tired of it, we’ll start to call them carelessly. Both scenarios are rather not optimistic.

3. Use one variable

By modifying the approach described above we can create one variable that will in turn store each transformation result.

We got rid of the series of variables and the hassle of naming. However, there is another problem. We introduced a mutating variable. After all, that’s not what we meant when we decided to write a functional code, right?

4. Currying and composition

Want to read more? Check out full version

--

--

InventiStudio
0 Followers

https://inventi.studio — We are Vue.js & Node.js web development agency based in Wrocław.