Functional Programming (FP)
Functional Programming (FP) defines that data (states) and behavior (function) are distinctly different things and should be kept separate for clarity. So perhaps instead of one giant box to describe everything, like OOP, we have multiple boxes and not combined data and function into one piece or one object. Functions operate on well-defined data structures like arrays and objects, rather than actually belonging to that data structure like object. It is about packaging our codes into separate chunks so that everything is well organized in each part of our code and concern itself with one thing it is good at. FP works really well when it comes to distributed computing where there is multiple machines interacting with data and parallelism where machines working on the same data at the same time.
Pure Function
If we break down FP, it all come down to these concept of pure functions. In pure functions, there are two main things:
The function cannot modify anything outside itself, meaning no side effect
Function always return the same output given the same input
And that's one of the problems with having side effects is that reusing shared state, like a global variable that can interact with anything and the order of the function calls matter and that can cause a lot of bugs.
Is it possible to have pure functions?
As a matter of fact input that return output is a side effect that is communicating with the outside world, so technically it is not pure. Pure functions which are just functions that do something on the inside and the outside world knows nothing about is well, it doesn't do anything because a program cannot exist without side effects.
Thus, the goal of functional programming is not to make everything pure functions, but to minimize side effects. The idea is to organize your code where there is a specific part that has side effects (isolate them), but when you have a bug, you know right away to go to that spot because that's where the side effects are happening. As for the rest of your code, since those are just pure functions, we don't have to worry about them as much.
How to define perfect functions?
One task only => function should do 1 task only. No massive function
Return statement => always return output
Pure functions
No shared state => means having no shared state with other functions
Immutable state => Once something is created, it cannot be changed. We avoid things like shared state. We can modified some of the state within our functions but we always return a new copy of that output. We never just modify our global state
Composable
Predictable => If we understand with 100 percent certainty what our functions do, it makes our code predictable
Last updated
Was this helpful?