Imperative vs. Declarative Programming Paradigm
Before we get into these two paradigms, I'll mention a few popular paradigms for you to explore later.
In this article, we will only discuss the imperative and declarative paradigms.
Imperative and Declarative Paradigms Through English Language
Imperative Style:
This paradigm is like giving step-by-step instructions It focusses on the "how" of the actions that must be taken to reach a goal.
Example:
Imagine you want to give someone instructions to make a cup of tea. An imperative approach would be:
Here, you are defining each step that must be followed in order to prepare the tea.
Declarative Style:
This paradigm is more about stating the desired outcome without explicitly listing all the steps to achieve it. It focuses on the "what" the result you want.
Example
Using the same scenario of making tea, a declarative instruction might be:
Here, you're defining the final goal without specifying each step that must be taken to get there. The person making the tea is aware of the procedures, therefore you don't have to explain them clearly as the one providing the directions.
领英推荐
Imperative and Declarative Paradigms Through Java Language
Let's now use Java programming examples to apply these paradigms to computer programming.
Imperative Style:
This involves writing code that describes in explicit detail how the program should archive its goals. It involves changing the state and using loops, conditionals, and variables to control the flow of the program.
Example:
Filter a list of integers to keep only the even numbers.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FooBar {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = new ArrayList<>();
for (Integer number : numbers) {
if (number % 2 == 0) {
evenNumbers.add(number);
}
}
System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
}
}
Declarative Style:
on the other hand, it focuses on what the program should accomplish without describing how to do it in detail. It is often more abstract and allows the underlying system to determine the best way to achieve the desired outcome.
Example:
Filter a list of integers to keep only the even numbers.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FoorBar {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evenNumbers = numbers.stream()
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
}
}