The rise of declarative programming

Mitul Vaghela
3 min readAug 19, 2020
image credit : Vladislav Babienko

Since quite some time now, we are seeing more and more frameworks and programming languages adding declarative programming constructs. React and Angular frameworks are full of them. While support for declarative programming in these frameworks only helps users of these frameworks, lately programming languages like Java and JavaScript have also started adding such constructs as core language features. This has fundamentally changed the way we write and comprehend code.

So what on earth is Declarative programming? And, how is it different from traditional approach?

The traditional programming style is called Imperative programming.

In Imperative programming style, the focus is on HOW things are done. While in the Declarative style, the focus is on WHAT we are trying to do.

Let’s understand this through an example. Suppose, we are given a list of integers and asked to double the integers that are greater than 5 and return the new list.

In the Imperative programming world, we will write like this (your approach could vary but its more or less same) -

Read through the lines of code written in DoubleValueGt5. We looped through each element of the list, checked if its greater than 5, if its true we multiply by 2 and store it in a new list. Finally, we return the new list. Note that the entire time, focus was on HOW to do this task.

Now, lets solve the same problem using declarative style -

BAAMMM! For those of you who has never seen this style of writing code, did you get goosebumps? Well, at least I did when I saw this for the very first time.

Let me control my emotions for moment and explain the code.

Again, read through the code in written in DoubleValueGt5 and you will notice that the focus has shifted from HOW to WHAT we are trying to do. We want a new list of integers that are greater than 5 and doubled. And, thats exactly what we have written.

As demonstrated, Declarative style of programming focuses on WHAT part of the code rather than HOW. It helps you write concise and readable code. The declarative style aligns with the way a human mind thinks and hence code can flow freely in your thought. The benefits of faster code review and easier code maintenance are tremendous.

Would you use declarative style of programming?

Originally published at http://mitulvaghela.com on August 19, 2020.

--

--