Declarative vs Imperative: Philosophy and Examples
You'll learn: How declarative programming describes what you want to achieve, while imperative programming specifies how to achieve it step-by-step.
The Core Philosophy
Think of ordering at a restaurant. An imperative approach is like giving the chef detailed instructions: "First, chop the onions. Then heat oil in a pan. Add onions, stir for 3 minutes..." You're controlling every step.
A declarative approach is simply saying: "I want the pasta carbonara." You describe the desired outcome and let the chef figure out the steps.
In programming, imperative code tells the computer how to change state through explicit commands—assignments, loops, conditionals. You've seen this throughout lessons on mutable state, sequential control flow, and statement-oriented syntax.
Declarative code expresses logic and desired results without dictating control flow. The system determines the execution strategy.
Comparing the Styles
Imperative example concept (building on previous lessons):
- Use variables and assignment
- Write explicit loops
- Mutate state step-by-step
- Control sequence matters
Declarative example concept (from functional lessons):
- Use higher-order functions like
mapandfilter - Describe transformations, not loops
- Compose operations
- Order often doesn't matter to the programmer
For instance, using map to transform a list is declarative: you say "apply this function to all elements," not "initialize counter, loop while counter less than length, increment counter..."
Why It Matters
Declarative code often reads closer to the problem domain, making intent clearer. Imperative code gives you fine-grained control but requires managing more details.
Key Takeaway: Declarative programming focuses on what outcome you want, while imperative programming specifies how to achieve it through explicit step-by-step instructions—each approach offers different tradeoffs in clarity, control, and abstraction level.