Imperative vs declarative programming

Before I explain what is imperative and declarative I will show you some code scenarios.

There are apples and oranges in a basket. I want to count apples in the basket.

case 1:

List<String> basket = Arrays.asList("orange", "apple", "orange", "orange", "apple");
int appleCount = 0;
for (String obj : basket) {
if (obj.equals("apple")) appleCount++;
}
System.out.println("There are " + appleCount + " apples in the basket.");

case 2:

List<String> basket = Arrays.asList("orange", "apple", "orange", "orange", "apple");
long appleCount = basket.stream().filter(obj -> obj.equals("apple")).count();
System.out.println("There are " + appleCount + " apples in the basket.");

the result of both got the same.

There are 2 apples in the basket.

use case 1:

you how the code work, how the code loop, how the code count apple.

use case 2:

you don’t know how the code work but just know what the code does, you don’t know how to loop or how to count on the code, just see the name of function.

use case 1 was written in imperative programming style.

use case 2 was written in declarative programming style.

so

Imperative ~ how does the code work

Declarative ~ what does code work (don’t care how)

Imperative style advantages

  • easy to read in simple function
  • beginner friendily

Imperative style disadvantages

  • hard to read when the code complex.
  • more code, more bug.

Declarative style advantages

  • short code, less bug
  • can write function when you don’t know logic inside (such as mock function)
  • easy to read when the code complex (if the programmer understand how the function work)

Declarative style disadvantages

  • not beginner friendly
  • hard to find someone who understand the code
  • can’t control performance (when you use built-in or external library)

Summary

In many code, there has mix the two type of code. you can choose what type of code you want to use more. one thing I suggest to consider, if you want to use declarative style with built-in or some libraries please check the understanding of your teammate or newcomer. maybe it have to take time to teach their. if you hard to find developer who understand declarative style, please consider use imperative style, it’s fine.

Thank you for reading & enjoy your coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s