Imperative programming pattern

Imperative Programming Paradigm

Imperative programming paradigm is one of the oldest programming paradigm. It is based on the idea of variables and assignments and focuses mainly on how to achieve a goal by performing step by step operations, changing the state of the program at each step. Programs following imperative paradigm are more efficient since our machines are designed based on Von Neumann Architecture which is intrinsically imperative. The machine code that the computer executes are imperative by style. Because of this, imperative paradigm is a widely used to write system software.

In this blog post, let’s dive in deep about Imperative programming paradigm. We will be covering the below properties of Imperative paradigm.

Variables and Assignment

In Imperative programming paradigm, variables play a crucial role. They are abstractions of memory cell that holds the value in the memory for the program to execute. Assignment statements are used to assign values to the variables during execution. Same variable can be reassigned with different values changing the state of the program during the course of execution.

int a, b, c;
a = 10;
b = 20;
c = a + b;
System.out.println("c: " + c);
b = 30;
c = a + b;
System.out.println("c: " + c);

Output
c: 30
c: 40


Execution of imperative programs

In an imperative program, we declare variables and write ordered sequences of commands. A command contains expressions that can compute and assign values to variables during execution. Multiple expressions can share a value. When an expression changes a variable, it affects all other expressions that uses that variable.

int a = 10, b = 20, c, d, e;
c = a + 20; // Expression 1
d = b + 30; // Expression 2
e = c + d; // Expression 3

In the above snippet, there are 5 variables and 3 expressions.

  • We have initialized variables a and b with values 10 and 20 respectively.
  • Expression 1 executes and assigns value 30 to c. Note that it uses the variable a.
  • Expression 2 executes and assigns value 50 to d. Note that it uses the variable b.
  • Expression 3 executes and assigns value 80 to e. Note that it uses the variables c and d. This expression depends on expressions 1 and 2.

Imperative paradigm are stateful

As mentioned above, variables store the state data of a program. Since variables can be shared, when an expression manipulates a variable, it affects the behavior of other expressions that are going to use these variables creating dependencies between the expressions. Check out this post to know more about being a stateful program.


Order of execution

In an imperative paradigm, the order of execution is crucial and the execution occurs in a sequential order. Changing the order of commands can lead to side-effect which can alter the behavior of the program.

How order can affect a program?

Meet Ron. Ron wrote the below program to swap values between variables. What Ron did not notice is that he messed up the order.

int a = 10, b = 20, holder;
a = b; // Expression 1
holder = a; // Expression 2
b = holder; // Expression 3
System.out.println("a: " + a + " b: " + b);

Output
a: 20 b: 20

What happened in the above program?

Imperative programs execute the expressions one by one in the given order. In the above program, Expression 2 should should precede Expression 1. Since imperative programs are stateful, wrong order in the above program lead to a bizarre behavior.

Ron got the order wrong. Don’t code like Ron. Code with the right order in imperative programs.

Side effects

A side effect occurs when an expression or function changes the value of a non-local variable or a variable outside it’s own scope (like global variable). An unpredictable side effect can make it hard of us developers to debug the program 😓.

public class SideEffect {
    private static int data;
    private static void clear() {
        data = 0;
    }
    public static void main(String[] args) {
        System.out.println(data++);
        System.out.println(data++);
        System.out.println(data++);
        clear();
    }
}

Output
0
1
2

In the above example, I print and increment data thrice and then reset it to 0 by calling the clear method. Every time data++ and data = 0 are executed, the state of the program changes.

What if I change the order ?

public class SideEffect {
    private static int data;
    private static void clear() {
        data = 0;
    }
    public static void main(String[] args) {
        System.out.println(data++);
        System.out.println(data++);
        clear();
        System.out.println(data++);
    }
}

Output
0
1
0

I get the above output. I wanted to get 0 1 2 but I got 0 1 0. Changing the order by moving clear a step above messed with the state of the program causing a side effect.


Repetition

When a same set of commands are required to be executed n number of times, we do not have to repeat it n times. Instead, imperative languages provide iterative constructs like loops which iterates the commands n number of times till a condition is met.

public class Repetition {
    private static void nonRepetative() {
        int sum = 0;
        sum += 1;
        sum += 2;
        sum += 3;
        sum += 4;
        sum += 5;
        System.out.println("nonRepetative"+sum);
    }
    private static void repetative() {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
        }
        System.out.println("repetative "+sum);
    }
    public static void main(String[] args) {
        nonRepetative();
        repetative();
    }
}

Output
nonRepetative 15
repetative 15

The above example has two methods nonRepetative and repetative. The goal is to find the total sum of the numbers 1 to 5. The nonRepetative method adds 1, 2, 3, 4 and 5 as separate commands while repetative method iterates over for loop to execute the addition command. The variable sum is created outside the loop and is changed during each iteration. Once the end condition i <= 5 is met, the loop terminates leaving the variable sum with value 15.

We are almost finished here. So what’s with imperative strictly follows execution orders? Why are they even stateful?

The reason is, this paradigm is tightly bound to the computer architecture. What may be the language we use to code, in one way or the other it compiles into a machine code. This machine code is the mother tongue of the processor. More on this can be found here.

Well, that’s it from me about Imperative Paradigms. I plan to keep this post updated with any new information that I find.


I hope this post was helpful 😊. If you find this post informative, support us by sharing this with fellow programmers in your circle 😀.

For any suggestions, improvements, reviews or if you like us to cover a specific topic, please leave a comment.
Follow us on twitter @thegeeksclan and in Facebook.
#TheGeeksClan #DevCommunity

error

Enjoy this blog? Please spread the word :)