Imperative VS Declarative Programming Part 1

In this tutorial, you will learn more about Imperative vs Declarative styles of programming in Java.

Imperative Style of Programming

The Imperative style focuses on how to get the result that we want, and how to perform some operations.
It embraces changing the object’s state. We mostly work with mutable objects.

This style represents a list of steps on how to perform some operations.
We are required to write the code of what needs to be done in each step.

It is mainly used in Object-Oriented Programming.

Declarative Style of Programming

This style of programming focuses on what is the result we want. It doesn’t bother with how to get that result.

We can concentrate on defining the input and output rather than the program steps.

The Declarative style embraces object immutability which improves program stability.

Since Java 8, we have a lot of functions that are part of existing libraries, which we can use without worrying about how the data is processed behind the scenes.

Functional Programming uses the concept of Declarative Programming.


Imperative vs Declarative programming examples

We will write a couple of programs in both Imperative and Declarative ways, so you can see the difference in the code.

Program 1:
Iterate over the elements of an array, sum all even numbers, and return the result as a long.

Imperative Style

class Test {

  public static void main(String[] args) {

    int[] array = {7, 8, 12, 41, 13, 98, 12, 18, 15, 72, 65, 90, 39, 40, 81, 10};

    long sum = 0;

    for (int i = 0; i < array.length; i++) {
      if (array[i] % 2 == 0) { // the way to find out if number is even
        sum += array[i];
      }
    }

    System.out.println("The sum of all even numbers is: " + sum);
  }
}

Output: The sum of all even numbers is: 360


Declarative Style

class Test {

  public static void main(String[] args) {

    int[] array = {7, 8, 12, 41, 13, 98, 12, 18, 15, 72, 65, 90, 39, 40, 81, 10};

    long sum = IntStream.of(array)
           .filter(num -> num % 2 == 0)
           .mapToLong(i -> i)
           .sum();

      System.out.println("The sum of all even numbers is: " + sum);
  }
}

Output: The sum of all even numbers is: 360


Program 2:
Write a program that will take an array of strings, go through all the elements, select only those that are longer than 5 characters, sort and return them as a new list.

Imperative Style

class Test {

  public static void main(String[] args) {

    String[] names = {"Josh", "Melissa", "James", "Robert", "Jim", "Alexander", "Tom"};

    List<String> resultList = new ArrayList<>();

    for (String element : names) {
      if (element.length() > 5) {
        resultList.add(element);
      }
    }

    // now sort the list
    for (int i = 0; i < resultList.size(); i++) {
      for (int j = resultList.size() - 1; j > i; j--) {
        if (resultList.get(i).compareTo(resultList.get(j)) > 0) {
          String temp = resultList.get(i);
            resultList.set(i, resultList.get(j));
            resultList.set(j, temp);
        }
      }
    }

    // print the elements of a list
    for (String name : resultList) {
      System.out.println(name);
    }
  }
}

Output: Alexander Melissa Robert


Declarative Style

class Test {

  public static void main(String[] args) {

    String[] names = {"Josh", "Melissa", "James", "Robert", "Jim", "Alexander", "Tom"};

    List<String> resultList = Stream.of(names)
             .filter(name -> name.length() > 5)
             .sorted()
             .collect(Collectors.toList());

    resultList.forEach(name -> System.out.println(name));
  }
}

Output: Alexander Melissa Robert


See how much more readable the code is and how much easier it is to understand the code written in Declarative style.
In most cases, we will not have to write the logic, but we can use many already defined functions, without being interested in what is happening behind the scenes.

In these examples, we used Streams APIs and Lambda expressions.
We will cover them in detail in later tutorials.

Happy coding!

 

 

Leave a Reply

Your email address will not be published.