Categories
Codes General

Coding Style: Imperative vs Declarative

“You know, imperative programming is like how you do something, and declarative programming is more like what you do, or something.”

Introduction

Let’s get to the first question. For whom do you code your program? Is it for yourself, for the computer, or for the other programmers?

There are two main tendencies in programming. The first, or the how, is to code the program to be more suitable for computer. And the second one, the what, is to code the program to be more readable by humans.

The first tendency: the how, is the imperative style.
And the other: the what, is the declarative style.

That’s all for the simple definitions, let’s get to the difference in detail.

What’s the difference?

General Daily Examples

Let’s get back to the basics. Remember the first time you learn about algorithm? A detailed step-by-step instructions to get you from point A to B. That is imperative. On the other hand, the result of the instructions, the what, is called declarative.

Is it still difficult to understand? OK then, let’s learn from examples. Because learning from examples is simpler compared to learning from definitions.

Suppose there is a question: How does one eat food?

An answer with the imperative approach is like this:

  1. Grab a fork.
  2. Stab the food with the fork.
  3. Make sure the food is liftable after stabbed.
  4. Lift the food to your mouth, make sure it does not fall.
  5. Bite and pull the food from the fork.
  6. Chew the food until it’s soft.
  7. Swallow the food.
  8. Repeat step 2-7 until you are full.

See, it’s like the first day algorithm class. A detailed step by step on how one does the activity. It shows a detailed way for someone or something, maybe androids, to eat.

Then, the answer for the declarative approach is:

  • Put the food inside one’s body from the mouth.

Yes, that’s it. The declarative answer only concerns about the what. Like a summary. Remember those times when you ask people or being asked by your boss to do something? “I brought you pizza,” or “Deliver this to our client.” These are declarative statements.

An interesting thought is that a declarative approach is made of layers of imperative approach. For example, if you don’t know how to “Deliver this to our client”, you would ask “How am I going to get there?”, “What is the address?”, “Which ride should I take?”, and many other questions. You subconsciously build the imperative to complete the declarative.

Now that you understand, let’s get to the code.

Code Examples

I’m going to use my favourite programming language, JavaScript, for the snippets here. Suppose that we want to search for a string in an array. Here is the imperative approach:

const arr = ["Adam", "Bard", "Eric", "Felix", "Gareth"];

let result = false;
for (let i = 0; i < arr.length; i++){
  if (arr[i] === 'Eric') {
    result = true;
    break;
  }
}

if (result === true){
  console.log('Eric found in array');
}
else if (result === false){
  console.log('Eric not found in array :(');
}

There, the rather long code does the work well, finding ‘Eric’ in the array. This is the imperative approach. We cannot read it in the first glance, but we have the step-by-step approach on finding the string:

  1. Iterate each value in an array.
  2. Move to the next value, if a value does not equal ‘Eric’.
  3. If a value equals ‘Eric’, set result as true and break the loop
  4. If the result is true, print “Eric found in array”.
  5. But, if the result is false, print “Eric not found in array :(“.

Now, let’s modify the logic to a declarative approach:

const arr = ["Adam", "Bard", "Eric", "Felix", "Gareth"];

const result = arr.includes('Eric');

if (result === true){
  console.log('Eric found in array');
}
else if (result === false){
  console.log('Eric not found in array :(');
}

With the help of the Array.prototype.includes() of JavaScript, writing a code to find a string become easier. The result is also easier to read. All the detailed code simplified in one function.

Why I prefer declarative style

I like the declarative approach better because first, it’s more readable because it’s closer to the human language, English. Therefore, it is easier for new programmers who touch the code for the first time.

Second, less lines. But, it gives the same results. Less is more.

Third, it is reusable. The same logic can be used on the other parts of the code with the confidence it will give the same result. Which means there will be less testing for the same code. And applied changes in one place will affect all parts of the code!

Conclusion

In my opinion, with the rapid growth of computer hardware, complex systems can be developed with less efficiency but more maintainable. One way to maintain them is to write the code in the declarative style.

When the code is human readable, one will write less documentation, get less call and emails, and less curses from other programmers who continue the legacies.

An exception is when you need efficiency in the program, such as when you have a limited hardware to execute the code. Or, probably time.

That’s it for this post. Hope you learnt something new, Live your code to code your life!

In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.

By Ericko Yap

Just a guy who is obsessed to improve himself. Working as a programmer in a digital banking company. Currently programming himself in calisthenics, reading books, and maintaining a blog.

Leave a Reply

Your email address will not be published. Required fields are marked *