What is the difference between imperative and declarative programming?
sobes.tech AI
Answer from AI
Imperative programming describes how to do something by specifying a sequence of steps. Declarative programming describes what needs to be done without delving into implementation details.
- Imperative: Focuses on control flow and state changes of the program. You tell the computer how to transition from one state to another.
- Declarative: Focuses on the logic of computations, not explicitly describing control flow. You tell the computer what you want to achieve.
Examples:
-
Imperative approach to finding even numbers in a slice:
// Imperative approach func findEvenImperative(nums []int) []int { var evenNums []int // Declare variable for result for _, num := range nums { // Iterate over elements if num%2 == 0 { // Check condition evenNums = append(evenNums, num) // Add to result } } return evenNums // Return result } -
Declarative approach (for example, using SQL, which is declarative by nature):
Although Go itself is largely imperative, the idea of declarativity is illustrated in a database query:
-- Declarative approach (SQL) SELECT * FROM numbers WHERE number % 2 = 0;Here, we simply declare that we want to retrieve all rows from the
numberstable wherenumberis even, without describing how the database should do this (e.g., which search or filtering algorithm to use).
The main differences can be summarized in a table:
| Property | Imperative programming | Declarative programming |
|---|---|---|
| Focus | How to do (sequence of steps) | What to do (desired result) |
| Control flow | Explicitly managed by the programmer | Hidden or abstracted |
| State | Actively changes | Less explicitly changed or immutable |
| Examples | C, Java, Python (mainly), Go | SQL, HTML, CSS, React (JSX) |
In Go, the imperative style is more common, but the concepts of declarativity appear in certain approaches, for example, when using libraries for data handling or in configuration descriptions.