DEV Community

KarthikSiddarth
KarthikSiddarth

Posted on • Updated on

First Chapter - Why Functional Programming?

This is notes on First chapter of the book Functional Light JavaScript written by Kyle Simpson.

This Chapter tells the purpose of using Functional Programming style while writing JavaScript.

Confidence:

`Code that you cannot trust is the code that you don’t understand, also the code that you don’t understand is the code that you cannot trust.`

The above quote says if you can’t understand or trust a code, then you can’t have any confidence.

What is Trust in this context? You should be able to verify the code just by reading and reasoning without executing it.

Code should be written in such a way that when the author or others read it, they should know the impact that the code will create if it is executed.

The techniques that form the foundation of Functional Programming will help the authors to write code in such a way that the author or others can gain confidence in the code just by reading and reasoning.

The biggest selling point of Functional programming is that code written in Functional programming style will have very few bugs and the bugs will exist in obvious places, makes it easier to find and fix it.

Communication:

The most important role of code is a means of communication to other humans.

It is estimated that 70% of time in code maintenance is spent reading the code. The global average number of lines written by a programmer per day is just 10 lines.

This can be prevented by considering Readability as an important factor while writing the code.

Readability score of code increase with the familiarity of code.

If our concern is making the code more readable and understandable, then Functional programming is the goto solution.

Once you learn what map(..) does, you will be able to understand instantly what it will do but incase of for(..) loop, every time the reader may have to go through the entire loop to understand what the code will do.

More recognizable code reduces the time to spend reading, understanding the code. This gives the reader time to focus on higher-level logic.
Readability:

Readability graph

Readability is not a binary characteristic.

Readability depends on the relation the reader has on the code.

Imperative code:

    var numbers = [4,10,0,27,42,17,15,-6,58];
    var faves = [];
    var magicNumber = 0;

    pickFavoriteNumbers();
    calculateMagicNumber();
    outputMsg();                // The magic number is: 42

    // ***************

    function calculateMagicNumber() {
        for (let fave of faves) {
            magicNumber = magicNumber + fave;
        }
    }

    function pickFavoriteNumbers() {
        for (let num of numbers) {
            if (num >= 10 && num <= 20) {
                faves.push( num );
            }
        }
    }

    function outputMsg() {
        var msg = `The magic number is: ${magicNumber}`;
        console.log( msg );
    }

Declarative code:

    var sumOnlyFavorites = FP.compose( [
        FP.filterReducer( FP.gte( 10 ) ),
        FP.filterReducer( FP.lte( 20 ) )
    ] )( sum );

    var printMagicNumber = FP.pipe( [
        FP.reduce( sumOnlyFavorites, 0 ),
        constructMsg,
        console.log
    ] );

    var numbers = [4,10,0,27,42,17,15,-6,58];

    printMagicNumber( numbers );        
    // The magic number is: 42

    // ***************

    function sum(x,y) { return x + y; }
    function constructMsg(v) 
    { return `The magic number is: ${v}`; }

Imperative code focuses on precisely instructing the computer how to do something.

Declarative code focuses on telling the computer What to do.

The first snippet, which is under Imperative code. The snippet is filled with if statements, for loops, temporary variables, reassignments, value mutations, function calls with side effects, and implicit data flow between functions.

The second snippet, which is under the Declarative code. It doesn’t contain most of the things that are present in the first snippet. Instead, it employs well known and trustable Functional programming techniques like filtering, reduction, transducing, and composition.

In the second snippet, the focus shifts from low-level logic to high-level logic.

Instead of messing with if statements, the task of filtering numbers is given to gte(…) (greater than equal to) and focus on more important tasks like combining the filters and summation function.


Converting to the functional programming style is a slow iterative process.

Functional programming is a very different way of thinking about how the code should be structured, to make data flow much more obvious and help the readers to follow your thinking.

The best code is the code that is most readable in the future because it strikes exactly the right balance between what it can/should be (idealism) and what it must be (pragmatism).

We shouldn't be content to write code that we anxiously hope works, and then abruptly breathe a sigh of relief when the test suite passes. We should know what it will do before we run it, and we should be absolutely confident that we've communicated all these ideas in our code for the benefit of other readers (including our future selves).

Top comments (1)

Collapse
 
jimmyjansen93 profile image
Jimmy Jansen

While I definitely do agree with how useful functional programming can be and much of your article is spot on in this, I do not agree with your examples...

A way better way (imo) to write this would be

const numbers = [4,10,0,27,42,17,15,-6,58]

const fromFavNums = (nums) => nums.filter(num => num >= 10 && num <= 20)
const generateMagic = (nums) => nums.reduce((a,b) => a + b)
const output = (num) => console.log(`The magic number is: ${num}`)

output(generateMagic(fromFavNums(numbers)))

While this is a purely functional style it does not use any libraries, reading it is like reading English.