/
Tech-study-notes

Programming paradigms

Imperative vs Declarative

Programming paradigms

Programming paradigms describe coding on different levels of abstraction:

Examples

Here is an example computation (summing the income by gender, from a suitable data source).

Imperative programming

var income_m = 0, income_f = 0;
for (var i = 0; i < income_list.length; i++) {
    if (income_list[i].gender == 'M')
        income_m += income_list[i].income;
    else
        income_f += income_list[i].income;
}

Notice:

Declarative programming

select gender, sum(income)
from income_list
group by gender;

Notice:

Functional vs procedural

Functional and procedural programming paradigms are extensions of the concept of declarative and imperative programming paradigms.

Subroutines

Both functional and procedural programming have some kind of subroutines: one uses functions, the other procedures.

Subroutines that are used for re-executing a predefined block of code. The difference between them is that functions return a value, and procedures do not. More specifically, functions are designed to have minimal side effects, and always produce the same output when given the same input. Furthermore, functions are usually concerned with higher level ideas and concepts. Procedures on the other hand do not have any return value, their primary purpose is to accomplish a given task and cause a desired side effect. (this basically goes back to the examples already shown earlier).

The desired computation is specified by composing functions (in functional programming). Composition means chaining two or more functions together by specifying how the output of one is fed as the input to the next (typically by writing one inside the other) Finally the whole composition, which is still itself a big function, is applied to the available inputs to get the desired output.

Objects

Data structures in procedural languages are generally mutable, which means they can be changed. Most functional languages don’t allow you to change an object or variable after it has been created.