Reducing code complexity with functional programming
In this article, We will walk over a simple exercise which will help me to communicate my thought clearly
Suppose, we have a class Person as below
class Person {
name:string
age:number
}
Now, our task is to find all adult person’s name which means find all person’s names who has age gather than 17 years.
Let’s first do it object-oriented way and you will end up with a function something like below
function findAdultPersons(persons:Person[]):string[] {
const names = []
for(const person of persons) {
if(person.age>17) {
names.push(person.name)
}
}
return names
}
Now, Going with the functional programming way you can re-write the function as below
function findAdultPersons(persons:Person[]):string[] {
return persons.filter(person=>person.age>17).map(person=>person.name)
}
Okay, Let’s move ahead.
You might have heard different ways of computing code complexity. A couple of such methods are listed below
- Cyclomatic complexity
- NPath complexity
You can find more details about both of them in this article.
For the sake of simplicity, we will consider Cyclomatic complexity for our scenario as it is really easy to calculate. The Object-oriented findAdultNames has complexity value 3 whereas functional programming way findAdultNames has complexity value only 1 which is 66% lower compared to the object-oriented approach
Here, one can argue that the code with functional programming is looping the array multiple time and wasting CPU cycles. But it the era of cloud computing power is cheap and easily accessible on demand. On the other hand, the complexity of code is directly related to its readability and cleanness and easier to alter.
Please share your view in the comments.