Be declarative wherever possible

Dattatray Kale
Technogise
Published in
2 min readAug 19, 2019

Imperative programming focuses on describing how a program operates. Take an example of the below function “ isPresent “.

First example: Imperative way, Look implementation of isPresent function.

Of course, it searches a number (search term) in the numbers array and replies with true or false.

If you observe carefully, it focuses on how the number is searched.

It iterates each number one by one in an array of numbers and checks if criteria is fulfilled (HOW part: for/if). Eventually, it tells you if the number is present/not in the array.

Declarative programming, on the other hand, expresses the logic of a computation without describing its control flow.

Let’s look at the declarative way of searching a number in an array.

Declarative way: Any function from LINQ.

In the above code, the method Any (present on array data type), is an extension method provided by LINQ.

It determines whether any element of a sequence contains a given number. It does not tell you how it is searched. That part is hidden behind API: Any.

The benefit of declarative approach over imperative approach is improved readability of code.

Another example:

Second example: Imperative way. See containsAllMen function: focuses on describing how a program operates (Control flows are involved: iterate and if)

This function “ containsAllMen “ tells you how searching is implemented and control flow like if clause determine the condition.

Now see the declarative way, it is using lodash’s every to determine the condition.

The declarative way: Using `every` function from lodash.

Originally published at https://beingcraftsman.com on February 1, 2019.

--

--

Dattatray Kale
Technogise

Software Craftsman & Cloud Engineer with 13+ years' expertise. Proficient in React, Angular, .NET, Node.js, Java, AWS, Azure. Proven leader in team building.