This is part of a blog post series I am writing about functional programming.

Imperative and Declarative programming are two different styles we can use when writing code. Let’s use an example to understand each style.

We will write a function that takes an array of numbers and returns the sum of all of them:

public void Test()
    var numbers = new[] {1, 2, 3, 4, 5};
    Assert.Equal(15, Sum(numbers));


int Sum(int[] numbers)
    var result = 0;
    foreach (var number in numbers)
        result += number;
    return result;

In the imperative style we create a result variable initialized as 0 and then loop through the array. For each element in the array we will mutate the result variable appending the current element to it. At the end we return that result.


int Sum(int[] numbers)
    return numbers.Aggregate(0, (result, number) => result + number);

In the declarative style we take the array of numbers and Aggregate then using a simple sum. To achieve this we use the Aggregate function from C# linq. The function takes an initial value -the seed- which is 0 in our case. I kept the same variable names as in the declarative style so we can compare them easily.

By the way, Aggregate is usually called reduce in other languages, it’s just microsoft trying to be different..

DISCLAIMERS: The seed in Aggregate is optional, so it could be omitted in the example since the default of int in C# is 0. Also, there is already a Sum function in Linq which could simplify this code, but this is not the goal of this blogpost, I just wanted to compare both styles.

What vs How

The declarative style is more expressive than the imperative one. The declarative code tells WHAT my code is doing while the imperative tells me HOW my code is achieving something. When reading the imperative code I have to infer the WHAT from it. This is a problem. I don’t really care about the how, I just care about the what!

Declarative code is functional

Another big drawback of imperative programming is that it forces you to relay a lot on mutation and loops, two things that we won’t be able to use when working with pure functional languages.

First step towards functional

If you want to start embracing functional programming I would say that the first step will be to start using the declarative still as much as possible. Every modern language has this capability nowadays: C# has Linq, Java has the Streams API, Ruby has the Enumerable module, Javascript since ES6 Array has been extended with a good bunch of declarative methods, etc.

You can force yourself to write declarative style code by simpling following the rule of writing no loops. We will explore that in a later post.