📜 ⬆️ ⬇️

How does imperative programming differ from declarative

Prehistory


Not so long ago, I was actively looking for work and was browsing a bunch of websites with job openings / projects. On some of them, “pass-through” questions can be viewed before submitting a response.

Most were quite ordinary, such as “how many years have you been using the X framework?”, But one seemed interesting to me (I even responded to it, but I changed it).

This is actually the question from the title. And I decided to figure it out. And the best way to understand is, as you know, to explain. So welcome under cat.

What are the differences?


In order to describe the differences, you must first understand what it is in principle. In the free retelling.
')

Imperative style


This is a programming style where you describe how to achieve the desired result. For example, I write:

- put the pan on the fire;
- take two eggs (chicken);
- stab each;
- Pour the contents into the pan;
- Throw out the shell;
...

This is not a declarative style, but with a mixture of imperative.

Declarative style


This style in which you describe what kind of result you need.

Here I just write:

- cook scrambled eggs

And the recipient of such a message already understands what steps need to be taken for this.

Why is the example from the part about imperative really mixed with declarativeness? Well, if only because the recipient must know what a frying pan and eggs are.

JS example


My favorite example is this: given an array of numbers, you need to write a function that returns an array of numbers, where each number from the original array is doubled. Those. [1, 2, 3] -> [2, 3, 6]

Imperative style:

function double (arr) { let results = []; for (let i = 0; i < arr.length; i++){ results.push(arr[i] * 2); } return results; } 

Declarative style:

 function double (arr) { return arr.map((item) => item * 2); } 

All high-level programming languages ​​allow you to write in a mixed style and, in fact, even these two examples do not show a clear separation.

It is probably correct to call one style “more declarative” and the other “more imperative”.

Source: https://habr.com/ru/post/324688/


All Articles