There are two types of programming in general.
Imperative: With imperative programming, our code tells the compiler and users about how to do a task.
[2, 4, 6, 8]
Declarative: With Declarative programming, our code tells the compiler and users what to do.
[2, 4, 6, 8]
It is highly likely that for most of the programmers, the Imperative code looks more familiar and more readable than the declarative code. This is because we preferably learn Imperative code first. But most of you don’t know what declarative code brings to us. Declarative code comes with great benefits
- Readability: You know what we developers spend more time on reading code and not writing. First, we are creating an array arrAsNumbers that has numbers array only. Second, we are taking this array to filteredArray which has only even numbers.
As in declarative code, code is short and crispy and the developer can read at a time. So what we are doing is, we are converting array string value to number type. This gives us a new array which we are using to filter with an even function. So the output of our program is an array containing even numbers only.
Now you’ve to decide which one do you prefer. So writing readable code is the most important step in our programming. Declarative code is more readable than Imperative.
- Less bug: With functional programming, you will get great benefits that every developer dreams of and one of them is a few bugs. Because we are going to use pure functions (functions that give the same output for exact same input and don’t contain side effects) in functional programming. There should be fewer bugs.
- Testing: Testing is easier as we use pure functions that give us the same output if we give exactly the same input. We don’t have to deal with hidden state and side effects.
- Maintainability: Declarative code is more maintainable because In functional programming we play with functions that are pure functions. As pure functions depend only on their input parameters to produce their output. Debugging with pure functions is much easier. Because the functions with which we are going to play with, are proven functions or techniques. As proven functions contain fewer bugs and are easy to maintain.
The key takeaway is that we should learn functional programming to make our code more expressive, more robust, and more readable.