Let’s compare different language paradigms!

Two of them:

  • Imperative: Tell the ‘machine’ how to do something, and it will do it.
  • Declarative: Tell the ‘machine’ what you want to happen, and it will figure out how to do do it.

Example: Double all numbers in an array

Imperative

We tell the computer how to iterate to access and retrieve each element in the array, double it, and assign it back to the same element in the array.

numbers = [1, 2, 3, 4, 5]
for (i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i] * 2
}

Declarative

We tell the computer that we want to double each element, and the computer does it somehow.

numbers = [1, 2, 3, 4, 5]
numbers.map(i -> i * 2)

Example: Sum of numbers in an array

Imperative

numbers = [1, 2, 3, 4, 5]
sum = 0;
for (i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

Declarative

numbers = [1, 2, 3, 4, 5]
total = numbers.reduce(sum <- sum + i);

-- Haskell
total = sum [1, 2, 3, 4, 5]

Example: SQL Query Simple

Declarative

SELECT *
FROM MyTable AS T
WHERE T.attribute = 'example'

Imperative

MyTable = [{name: 'A', attribute: 'a'}, {name: 'B', attribute: 'b'}, {name: 'C', attribute: 'c'}]
T = MyTable
selection = []
for (i = 0; i < T.length; i++) {
  if (T[i].attribute == 'example') {
    selection.add(T[i])
  }
}

Example: SQL Query Intermediate

Declarative

SELECT *
FROM Employees
INNER JOIN Departments
WHERE Employees.department_name = Departments.name

Imperative

Departments = [{}, {}, {}, ...]
Employees = [{}, {}, {}, ...]
selection = []
for (i = 0; i < Employees.length; i++) {
  for (j = 0; j < Departments.length; j++) {
    if (Employees[i].department_name == Departments[j].name) {
      selection.add({employee: Employees[i], department: Departments[j]})
    }
  }
}

Summary

In the above examples, the declarative versions were always smaller and cleaner to read. But, unfortunately, it might not always be possible to use declarative style, especially for business logic.

Having said that, declarative code is just an abstraction over imperative code that isn’t seen by the developer. Functions in imperative code can reach much of the benefits as declarative code, though the developer would be forced to define how the task should be done.

Now a quick word from a tech company who helps support me and this site: