I. What Are Imperative Programming and Declarative Programming?
Imperative Programming and Declarative Programming are two different ways of expressing a program.
- Imperative programming: tells the computer which operations to perform and in what order to complete the task.
- Declarative programming: tells the computer what result is desired, without having to describe the specific execution steps in detail.
The core difference between the two is:
- Imperative programming focuses on How: how to implement it.
- Declarative programming focuses on What: what is to be achieved.
For example, suppose we need to filter out all numbers greater than 10 from a set of numbers.
Imperative approach:
numbers = [3, 12, 5, 18, 9, 20]
result = []
for number in numbers:
if number > 10:
result.append(number)
print(result)
The developer explicitly describes:
- Create a result list.
- Iterate through the original list.
- Check whether the current number is greater than 10.
- Add it to the result list when the condition is met.
- Output the final result.
Declarative approach:
numbers = [3, 12, 5, 18, 9, 20]
result = list(filter(lambda x: x > 10, numbers))
print(result)
Here, the filtering condition is mainly expressed; there is no need to manually describe how the result list is created or how elements are added one by one.
Both approaches achieve the same goal, but at different levels of abstraction.
Note that imperative and declarative are not two mutually exclusive categories of programming languages, but two programming philosophies. Many modern languages support both styles at the same time.
II. How Imperative Programming Works
1. What Is Imperative Programming?
Imperative programming describes how a program should complete a task through a series of explicit instructions.
It usually directly manipulates program state, controlling program execution through variable assignment, conditional checks, loops, and function calls.
For example:
balance = 1000
balance = balance - 200
balance = balance + 500
print(balance)
The program explicitly specifies:
- The initial balance is 1000.
- Deduct 200.
- Add 500.
- Output the final balance.
During program execution, the state of the variable balance keeps changing.
2. Basic Components of Imperative Programming
Variables and state
Variables are used to store data during program execution.
count = 0
count = count + 1
Sequential execution
Operations are executed in the order in which the code is written.
a = 10
b = 20
c = a + b
Conditional checks
Different code branches are executed based on conditions.
if age >= 18:
print("成年人")
else:
print("未成年人")
Loop control
Certain operations are repeated through loops.
for i in range(5):
print(i)
State modification
Data in the program is changed through assignment and operations.
user = {
"name": "Tom",
"age": 18
}
user["age"] = 19
Together, these mechanisms form the execution logic of an imperative program.
3. Execution Flow of an Imperative Program
flowchart TB
A["Program Start"] --> B["Initialize Variables"]
B --> C["Execute First Instruction"]
C --> D["Read Current State"]
D --> E["Perform Operation and Modify State"]
E --> F{"Are There More Instructions?"}
F -->|"Yes"| D
F -->|"No"| G["Output Result"]
G --> H["Program End"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4. Main Characteristics of Imperative Programming
- Clear execution steps: Developers need to describe specific operations.
- Intuitive state changes: Variables, objects, and data structures can be modified directly.
- Strong control: Loops, branches, memory, and execution order can be controlled precisely.
- Relatively low level of abstraction: Some implementation details must be handled by the developer.
- Easy to trace execution: Program state changes can be analyzed in the order of instructions.
5. Common Imperative Programming Languages
| Language | Typical Applications |
|---|---|
| C | Operating systems, embedded development |
| C++ | Game engines, infrastructure |
| Java | Enterprise applications, backend services |
| Go | Network services, cloud-native systems |
| Python | Automation, data processing, backend development |
| JavaScript | Web frontend, backend development |
These languages also support declarative programming styles; imperative expression is simply very common in them.
III. How Declarative Programming Works
1. What Is Declarative Programming?
Declarative programming lets the underlying system decide how to complete a task by describing the goal, rules, constraints, or desired state.
Developers usually do not need to specify each execution step in detail.
For example, SQL:
SELECT name, age
FROM users
WHERE age > 18
ORDER BY age DESC;
This SQL expresses:
- Query data from the
userstable. - Filter records with age greater than 18.
- Return name and age.
- Sort by age in descending order.
The developer does not explicitly specify:
- How to traverse the data.
- How to evaluate each record.
- What sorting algorithm to use.
- Whether to use an index.
- Whether to use parallel execution.
These tasks are decided by the database management system based on the query plan and runtime environment.
2. Basic Components of Declarative Programming
Goal Description
Describe the final result you want to obtain.
For example:
SELECT * FROM users;
It expresses querying all users rather than describing the operation of reading records one by one.
Rules and Constraints
Describe the conditions the system must satisfy.
For example, CSS:
.container {
display: flex;
justify-content: center;
align-items: center;
}
The developer declares layout rules, and the browser layout engine calculates the positions of elements.
State Description
Describe the state the system should reach.
For example, a Kubernetes configuration:
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web-app
template:
metadata:
labels:
app: web-app
spec:
containers:
- name: web
image: nginx:latest
This configuration declares a desired application with three replicas.
Developers do not need to manually write the steps for creating, monitoring, and recovering each container. The Kubernetes controller continuously reconciles the actual state with the desired state.
3. Execution Flow of a Declarative Program
flowchart TB
A["Describe the goal or desired state"] --> B["System parses the declaration"]
B --> C["Generate execution plan"]
C --> D["Underlying execution engine"]
D --> E["Execute specific operations"]
E --> F["Obtain execution result"]
F --> G["Check whether the goal is met"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that different declarative systems execute in different ways.
SQL query execution plans are usually generated by the database optimizer; CSS is handled by the browser's layout and rendering engine; Kubernetes continuously reconciles the actual state with the desired state through controllers.
4. Main Characteristics of Declarative Programming
- Focus on the end goal: Emphasis is on expressing what result is desired.
- Hide execution details: The underlying system handles the specific operations.
- Higher level of abstraction: Developers can reduce repetitive low-level implementation code.
- Focused expression: Business intent is described through rules, constraints, or queries.
- Depends on the execution engine: Actual execution efficiency and behavior are affected by the underlying system implementation.
5. Common Declarative Technologies
| Technology | Declared Content | Execution Entity |
|---|---|---|
| SQL | Data queries and filter conditions | Database engine |
| HTML | Document structure | Browser |
| CSS | Page style and layout rules | Browser rendering engine |
| React JSX | UI structure and component relationships | React runtime |
| Kubernetes YAML | Desired cluster state | Kubernetes controllers |
| Terraform HCL | Desired infrastructure configuration | Terraform engine |
| Regular expressions | String matching rules | Regular expression engine |
IV. Core Differences Between Imperative and Declarative
| Comparison Dimension | Imperative Programming | Declarative Programming |
|---|---|---|
| Core focus | How to complete the task | What result is desired |
| Mode of expression | Operation instructions | Goals, rules, constraints |
| Control | More in the developer's hands | More delegated to the underlying execution system |
| State management | Often explicitly modifies state | Usually describes goals or data relationships |
| Level of abstraction | Relatively low | Usually high |
| Implementation details | Requires more description | Usually handled by the execution engine |
| Flexibility | Can finely control the execution process | Constrained by the declarative model and execution engine |
| Typical technologies | Loops, assignments, conditionals | SQL, CSS, HTML, YAML |
1. Two Implementations of the Same Task
Suppose you need to calculate the total price of a set of products.
Imperative implementation:
prices = [100, 200, 300]
total = 0
for price in prices:
total += price
print(total)
The developer describes:
- Initialize the total amount.
- Iterate over the price list.
- Add the current price to the total amount.
- Output the final result.
Declarative style:
prices = [100, 200, 300]
total = sum(prices)
print(total)
Here, sum() is used directly to express the intent to calculate a sum.
The underlying function handles the iteration and accumulation.
Note that calling sum() does not mean the Python program has become a purely declarative program. It merely expresses the computational goal through a higher level of abstraction.
2. Levels of Abstraction in the Two Programming Paradigms
flowchart TB
A["Business Goal"] --> B["Declarative Description"]
A --> C["Imperative Description"]
B --> D["Declare Goals, Rules, and Constraints"]
D --> E["Execution Engine Determines the Implementation"]
C --> F["Describe Specific Execution Steps"]
F --> G["Developer Controls the Operation Process"]
E --> H["Obtain Result"]
G --> H
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Both approaches solve the same problem; they differ only in the division of responsibilities between the developer and the underlying execution system.
5. Typical Applications of Declarative Programming
Declarative programming is not just a theoretical idea; it is very common in modern software development.
1. SQL: Declaring Query Goals
SQL is one of the most typical declarative languages.
For example:
SELECT *
FROM orders
WHERE amount > 1000
ORDER BY created_at DESC;
This statement expresses the query requirements:
- Query orders.
- Filter records with amounts greater than 1000.
- Sort in descending order by creation time.
A database management system generates a query plan based on the table structure, indexes, statistics, and execution environment.
For example, the database may choose:
- Full table scan.
- Index scan.
- Index range scan.
- Sorting operation.
- Parallel execution.
Developers usually do not need to specify these details manually.
The Execution Mechanism Behind SQL
flowchart TB
A["SQL Query Statement"] --> B["Lexical and Syntax Analysis"]
B --> C["Semantic Check"]
C --> D["Query Optimizer"]
D --> E["Generate Execution Plan"]
E --> F["Database Execution Engine"]
F --> G["Return Query Results"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
There is an important concept here: being declarative does not mean the system does not need execution steps; rather, the execution steps are determined by the underlying system.
The database still needs to traverse the data, evaluate conditions, and perform sorting; it is just that the SQL user does not need to write these operations one by one.
2. HTML and CSS: Declaring Page Structure and Styles
HTML is used to describe page structure.
<div class="card">
<h2>User Information</h2>
<p>Welcome to the system</p>
</div>
CSS is used to describe page styles:
.card {
width: 300px;
padding: 20px;
background: #ffffff;
border-radius: 12px;
}
Developers declare element structure and style rules.
The browser is responsible for:
- Parsing HTML.
- Building the DOM.
- Parsing CSS.
- Computing styles.
- Computing layout.
- Painting the page.
- Compositing the final frame.
3. React: Declarative UI
React is an important representative of declarative programming ideas in modern front-end development.
Traditional imperative DOM operations:
const button = document.createElement("button");
button.textContent = "点击次数:0";
document.body.appendChild(button);
let count = 0;
button.addEventListener("click", () => {
count++;
button.textContent = `点击次数:${count}`;
});
Developers need to be clear about:
- Creating DOM elements.
- Setting text.
- Inserting into the page.
- Listening for click events.
- Modifying variables.
- Updating DOM content.
React declarative approach:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
点击次数:{count}
</button>
);
}
Developers describe:
- What the current state is.
- How the page should display based on the state.
- How user actions update the state.
React is responsible for coordinating UI updates based on state changes.
The core idea here is:
UI is a description of state; when state changes, the interface reconciles according to the new state.
Note that React is not entirely without imperative operations. Developers can still perform imperative operations through useRef, the DOM API, side-effect handling, and other means.
4. Kubernetes: Declaring Desired State
Kubernetes is an important example of declarative infrastructure management.
For example:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-app
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
This configuration declares:
- A Deployment is required.
- The application name is
nginx-app. - It is expected to run three replicas.
- It uses the specified container image.
The Kubernetes controller continuously compares the actual state with the desired state.
If a Pod exits abnormally, the controller attempts to recreate the Pod to bring the system back to the desired state.