✅ Write cleaner code using Functional Programming

What is it?

Functional programming is just a software engineering paradigm/convention of writing code. It is purely independent of the language in which it is written (ie) it can be applied to any language.

Why is it required?

  • To make code more readable & cleaner.
  • It improves the reusability of the code.
  • Makes it easy to test and debug.

2 Core principles of Functional Programming:

  • Pure functions

    Pure functions mean that the output of a function should be independent of the scope in which it is called/defined. In simple words, A function should return the same output every time when the input passed is same.

Let us consider this with an example,

goalsScored = 3
updateCount = 1

function updateGoalsScored(updateCount) {
    goalsScored = goalsScored + updateCount
    return goalsScored
}

updateGoalsScored(updateCount)  // output => 4 
updateGoalsScored(updateCount)  // output => 5

In the above code, the code returns different output even though the parameters passed are the same every time. Let us try to achieve the same using pure functions:

goalsScored = 3
updateCount = 1

function updateGoalsScored(goalsScored, updateCount) {
    return goalsScored + updateCount
}

updateGoalsScored(goalsScored, updateCount)  // output => 4 
updateGoalsScored(goalsScored, updateCount)  // output => 4

If you see the above code, the function will return the same output every time if the input is the same. It won't depend on the data which is outside the function. In short, the function should be independent and must not depend on the scope/data outside it.

  • First Class Citizens

The concept of first-class citizens always comes into the picture when we talk about functional programming. But what is first class citizens? It is simply nothing but treating functions as variables.

Basically, in FP, any function which is defined must be treated as a variable and should possess all the characteristics of a variable (ie) a function can be passed as a parameter, returned via function, etc.

// In FP, a function can be stored in a variable
variable functionName = function() { 
    // ...
    }

// It can be passed as an argument to another function
callAnotherFunction(functionName)

// It can be returned in a function 
function fetchAFunction() {
    // ...
    return functionName
}

Conclusion

What we saw above is just a gist of functional programming. And even by applying these above 2 principles, we can write more cleaner and readable code.

We will discuss more parts of functional programming in the upcoming blogs.