Imperative programming is a programming paradigm in which a program's state is modified by explicit statements.
It focuses on how a problem should be solved. Imperative code defines specific instructions for how a state should be manipulated and transformed to reach the desired outcome.
In the real-world example, tying your shoes, imperative programming instructions might look something like this:
- Find your shoes.
- Take your shoes to a location to sit.
- Sit down.
- Pick up your right shoe.
- Ensure the shoe laces are untied.
- Open up the shoe and so on.
Imperative code is explicitly defined and outlines exactly how to reach a certain outcome. What does this look like in code?
When writing code in Java or in Kotlin, imperative code is very familiar. When implementing functions, methods, or classes, the details and instructions are typically defined using an imperative style. There may be other programming paradigms mixed in, but generally much of the code will follow an imperative style.
The following is globally a simple example in Kotlin:
/**
* @return The sum of the numbers from 1 to n
*/
fun sumNumbersToN(n: Int) : Int {
var sum = 0
for (i in 1..n) {
sum += i
}
return sum
}
This example performs a summation from 1 to an input value N. The code very explicitly outlines how the desired summation will be performed. It's clear how the state, the sum variable, is mutated, and there is a clear flow to the operations performed. OOP comes under this category so let's have a look at that.