I. Basic Concepts of Pure Functions and Side Effects
Functional programming emphasizes breaking a program into computational units that can be reasoned about independently. The two most important concepts here are pure functions and side effects.
Pure function: The same input always produces the same output, and execution does not produce observable external effects.
Side effect: During function execution, in addition to returning the computed result, the function also produces an observable effect on the external environment.
For example:
def add(a, b):
return a + b
add is a pure function:
- The result depends only on the parameters
aandb. - The same arguments always yield the same result.
- It does not modify external variables.
- It does not access files, the network, or a database.
- It does not produce other observable effects.
Consider another function:
counter = 0
def increment():
global counter
counter += 1
return counter
increment is not a pure function:
- The function depends on the external variable
counter. - Each call may produce a different result.
- The function modifies external state.
The core differences between the two:
| Dimension | Pure function | Function with side effects |
|---|---|---|
| Input dependency | Explicit parameters | May depend on external state |
| Output determinism | The same input corresponds to the same output | The result may vary with the environment |
| External state | Does not modify external state | May read or modify it |
| Predictability | High | Depends on external conditions |
| Testability | Usually simpler | May require simulating the external environment |
| Cacheability | Suitable for caching by input | Requires additional checks |
| Concurrency safety | Easier to guarantee | Requires managing shared state |
| Composability | Usually stronger | Requires considering the order of side effects |
Note: reading external state and modifying external state are not the same thing. Strictly speaking, a pure function can neither depend on external mutable state that is not controlled by its parameters nor produce observable side effects.
II. Pure Functions
2.1 The Two Core Conditions of Pure Functions
A pure function must satisfy two conditions at the same time.
Condition 1: Determinism
For the same input, the function always produces the same output.
Mathematically, this can be expressed as:
When the input x remains unchanged, the output y also remains unchanged.
For example:
def square(x):
return x * x
print(square(5))
print(square(5))
print(square(5))
Output:
25
25
25
Condition 2: No Observable Side Effects
Function execution must not change external state observable by the caller, nor produce other externally observable effects.
For example:
def calculate_tax(price, rate):
return price * rate
This function only performs computation; it does not modify the passed-in object or access external resources.
2.2 Functions That Depend on Global Variables Are Not Pure Functions
tax_rate = 0.1
def calculate_tax(price):
return price * tax_rate
Although this function does not modify any variable, it depends on external state tax_rate.
If the tax rate changes, the same price may produce different results.
The dependency can be passed in explicitly:
def calculate_tax(price, tax_rate):
return price * tax_rate
Now the computed result depends only on two explicit parameters.
This refactoring has two benefits:
- Function dependencies are clearer.
- Input conditions can be directly controlled during testing.
2.3 Functions That Read Time and Random Numbers
Neither of the following two functions is a pure function in the strict sense:
import time
import random
def current_time():
return time.time()
def generate_code():
return random.randint(1000, 9999)
Reasons:
current_time()depends on the system clock.generate_code()depends on the internal state of the random number generator.
Even without explicitly modifying business variables, their results are not determined solely by the function parameters.
External dependencies can be turned into explicit inputs:
def format_timestamp(timestamp):
return f"Timestamp: {timestamp}"
def generate_code_from_seed(seed):
import random
rng = random.Random(seed)
return rng.randint(1000, 9999)
For the same timestamp or seed, the result can remain deterministic.
However, note that creating, using, and managing the state of random number generators still require explicit design. Passing a random seed as a parameter is only a common way to control nondeterminism; it does not mean that all random operations are inherently pure functions.
2.4 Formal Understanding of Pure Functions
A pure function can be abstracted as:
Where:
- X: the set of input values.
- Y: the set of output values.
- f: a deterministic mapping relationship.
From the perspective of functional programming, functions should not rely on implicit input, nor should they produce implicit output.
Pure functions in real programs also need to account for boundaries such as exceptions, termination, and resource consumption. For example, even if a function does not modify external state, if it may loop indefinitely, it cannot simply be considered to behave like an ordinary mathematical function under all program semantics.
III. Side Effects
3.1 Definition of Side Effects
A side effect is an observable impact on the program environment beyond the return value during the execution of a function.
For example:
def save_user(user):
database.insert(user)
The primary purpose of the function is not to compute a return value, but to write data to the database.
The database state has changed, so this is a function with side effects.
Side effects do not mean that the program contains an error.
Real software systems must interact with the outside world:
- Read user input.
- Access the database.
- Send network requests.
- Write to files.
- Update caches.
- Output logs.
These operations all require side effects.
The real problem to solve is not eliminating side effects, but controlling their scope and how they propagate.
3.2 Common Types of Side Effects
| Side Effect Type | Manifestation | Example |
|---|---|---|
| State modification | Modifying external variables or shared objects | Modifying a global counter |
| File operations | Reading, writing, or deleting files | Writing to a log file |
| Network operations | Sending requests or receiving responses | Calling an HTTP API |
| Database operations | Modifying persisted data | INSERT, UPDATE |
| Console output | Outputting information | print, console.log |
| Random numbers | Using random number generator state | random.randint |
| Time dependency | Reading the current time | Getting system time |
| Process operations | Creating processes or modifying the environment | Starting a subprocess |
| Messaging | Sending messages to a message queue | Kafka Producer |
| Exception interaction | Throwing exceptions or triggering external handling | Throwing a business exception |
3.3 Are Read Operations Also Side Effects?
This is a question that is easy to confuse.
From the strict definition of a pure function, reading external mutable state also breaks the determinism of a pure function.
For example:
def get_config():
return config_service.get("tax_rate")
Although it does not modify the configuration, the function depends on an external configuration service.
If the configuration changes, the same call may produce different results.
Therefore:
- Reading immutable constants usually does not break the determinism of a pure function.
- Reading external mutable state usually does not meet the requirements of a pure function.
- Modifying external state is a typical side effect.
- Accessing networks, files, and databases usually constitutes external interaction.
In engineering practice, both reads and writes are usually regarded as external effects that need to be managed.
IV. Execution Comparison Between Pure Functions and Side Effects
4.1 Execution Process of a Pure Function
The input-output relationship of a pure function is clear, and it does not depend on external mutable state.
flowchart TB
A["Receive explicit input"] --> B["Perform deterministic computation"]
B --> C["Produce computed result"]
C --> D["Return result"]
D --> E["External state remains unchanged"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4.2 Execution Process of a Side-Effect Function
In addition to computing a result, a side-effect function may also interact with the external environment.
flowchart TB
A["Receive input"] --> B["Execute function logic"]
B --> C["Access external resources"]
C --> D["Produce external effects"]
D --> E["Return result or execution status"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4.3 The Two Can Coexist in a Single Business Process
For example, an order system:
- Receive the order request.
- Query product information.
- Calculate the total product price.
- Calculate the discount.
- Write the order data.
- Send the payment request.
- Return the processing result.
Among these:
- Querying product information involves reading external resources.
- Total price calculation can be designed as a pure function.
- Discount calculation can be designed as a pure function.
- Order writing has side effects.
- Payment requests have side effects.
A good architecture will keep core business computation as pure as possible and concentrate external interactions at clearly defined boundaries.
V. Referential Transparency
5.1 What Is Referential Transparency
Referential transparency is an important property in functional programming.
If an expression can be replaced by the value it computes without changing the program's behavior, then that expression is referentially transparent.
For example:
def add(a, b):
return a + b
result = add(10, 20) * 2
Because:
the expression can therefore be replaced with:
result = 30 * 2
Before and after the replacement, the observable behavior of the program remains the same.
5.2 The Relationship Between Pure Functions and Referential Transparency
The two are closely related, but they emphasize different things.
| Concept | Focus |
|---|---|
| Pure function | Deterministic input/output and no observable side effects |
| Referential transparency | Whether an expression can be equivalently replaced by its computed result |
Calls to pure functions are usually referentially transparent.
For example:
def multiply(a, b):
return a * b
You can replace:
multiply(3, 4)
with:
12
But the following expression cannot be replaced in the same way:
import time
def get_time():
return time.time()
Each call may yield a different result.
5.3 The Engineering Value of Referential Transparency
Code refactoring
Complex expressions can be split apart or merged without changing the computation's semantics.
Cache optimization
Calls to a pure function with the same input can reuse the computed result.
Parallel optimization
Independent expressions can be computed in parallel, provided other resource constraints are satisfied.
Compiler optimization
Based on the language's semantics, a compiler can perform optimizations such as constant folding and common subexpression elimination.
Note that compiler optimizations are still constrained by factors such as language specifications and floating-point semantics; one cannot simply assume that every pair of seemingly identical expressions can be reordered at will.
VI. Immutability and Side-Effect Control
6.1 Problems Caused by Mutable Data
Consider the following code:
def update_user(user):
user["age"] = 30
return user
Call:
user = {
"name": "Alice",
"age": 20
}
result = update_user(user)
print(user)
print(result)
Output:
{'name': 'Alice', 'age': 30}
{'name': 'Alice', 'age': 30}
The function directly modifies the dictionary passed to it.
The caller may not know that user has already been changed, which can create implicit dependencies in the program's behavior.
6.2 Using Immutable Updates
You can create a new object:
def update_user(user):
return {
**user,
"age": 30
}
Call:
user = {
"name": "Alice",
"age": 20
}
result = update_user(user)
print(user)
print(result)
Output:
{'name': 'Alice', 'age': 20}
{'name': 'Alice', 'age': 30}
The original object remains unchanged, while the new object represents the updated state.
6.3 Relationship Between Immutability and Pure Functions
Immutability helps implement pure functions, but the two are not the same concept.
- Immutability concerns whether data can be modified.
- Pure functions concern input-output relationships and externally observable effects.
For example:
def calculate(items):
return sum(items)
Even if items is a mutable list, as long as the function only reads the data, does not modify it, and does not depend on other external state, it can still be a pure function.
Conversely, even if a function only operates on immutable objects, if it reads the current time or writes to a file, it is not a pure function either.
Therefore, immutability is an important design technique, but it is not a sufficient condition for pure functions.
7. Side Effect Isolation (Side Effect Isolation)
7.1 Why Isolate Side Effects
In large systems, side effects are unavoidable.
If all business logic directly accesses databases, networks, file systems, and global state, the code will develop complex environmental dependencies.
For example:
def create_order(user_id, product_id):
user = database.get_user(user_id)
product = database.get_product(product_id)
price = product.price
discount = discount_service.calculate(user, price)
database.save_order(user_id, product_id, price - discount)
payment_service.pay(user_id, price - discount)
This function simultaneously handles:
- Data queries.
- Business calculations.
- Discount calculations.
- Order persistence.
- Payment requests.
Any problem with an external dependency may affect the entire function.
Testing also requires preparing multiple dependencies, such as the database, payment service, and discount service.
7.2 Separate Pure Computation from External Interaction
Business calculations can be extracted into pure functions:
def calculate_discount(price, rate):
return price * rate
def calculate_final_price(price, discount):
return price - discount
External interactions are handled by the application service:
def create_order(user_id, product_id):
user = database.get_user(user_id)
product = database.get_product(product_id)
discount = calculate_discount(
product.price,
user.discount_rate
)
final_price = calculate_final_price(
product.price,
discount
)
database.save_order(
user_id,
product_id,
final_price
)
payment_service.pay(user_id, final_price)
Although the application service still has side effects, the core computation logic has been separated out.
This allows testing separately:
- Whether discount calculation is correct.
- Whether the final price is correct.
- Whether the order service correctly calls external dependencies.
- Whether correct exception handling is performed when payment fails.
7.3 Pure Computation and Side Effect Isolation Architecture
flowchart TB
A["External Request"] --> B["Application Service Layer"]
B --> C["Read External Data"]
C --> D["Build Business Calculation Input"]
D --> E["Pure Function Calculation Layer"]
E --> F["Return Calculation Result"]
F --> G["Application Service Layer Processes Result"]
G --> H["Persist or Call External Service"]
H --> I["Return Response"]
subgraph S["Side Effect Boundary"]
B
C
G
H
end
subgraph P["Pure Calculation Core"]
D
E
F
end
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style S fill:#F6FAF7,stroke:#DCE9E0,color:#64748B
style P fill:#F6FAF7,stroke:#DCE9E0,color:#64748B
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This reflects an important architectural idea:
Separate business decisions from external interactions.
The pure calculation core is responsible for answering what result the business rules should produce; the external boundary handles data reading, persistence, and system interaction.
8. Functional Core and Imperative Shell
The functional core and imperative shell (Functional Core, Imperative Shell) is a common software design pattern.
It emphasizes:
- Core business logic should be implemented using pure functions wherever possible.
- The outer application flow is responsible for input, output, and side effects.
- The two parts are connected through clear data interfaces.
8.1 Architectural Layering
| Layer | Main Responsibilities | Side Effects |
|---|---|---|
| Input Adapter Layer | Receives HTTP requests, messages, and commands | Yes |
| Application Service Layer | Orchestrates business processes | Usually yes |
| Pure Function Core | Business rules and calculations | No |
| Output Adapter Layer | Database, network, message sending | Yes |
8.2 Practical Example
Suppose we need to calculate the final order amount.
Pure function core:
def calculate_order_total(items, discount_rate, tax_rate):
subtotal = sum(
item["price"] * item["quantity"]
for item in items
)
discounted = subtotal * (1 - discount_rate)
total = discounted * (1 + tax_rate)
return round(total, 2)
Application service: