TL;DR
A function is supposed to take inputs and return an output. A side effect is anything else it does while running: changing a value that lives outside the function, writing to a file, printing a line, or sending a message to another machine. Side effects are often the whole point of a program, but they make a call depend on more than its inputs and make the call itself a change to the world, which is harder to test, repeat and combine safely.
Builds on: Pure Function for the case with no side effects, and Mutable State for the most common side effect, a change to a shared value · Leads to: Functional Programming, which pushes side effects to the edges of a program, and race conditions when several calls cause side effects at once
Where it's used
Logging and output. A program that prints a progress line, writes a log entry or saves a report to disk does all three as side effects. The result of the calculation is the same either way, but the printed line and the file are visible changes to the outside world.
Payments and email. A checkout function that charges a card and sends a receipt email has two large side effects. Running it twice by mistake charges the customer twice and sends two emails. Programmers guard these calls carefully because a repeated side effect cannot be taken back by running the function again.
Caches and counters. A function that counts how often it has been called keeps a number outside itself, often through a closure, and changes that number on each call. A web server that records each request in a shared counter does the same. These effects are small, but they mean two calls with the same input can return different answers.
How it works
Take two small functions that both take a number and return a number. The first has no side effect. The second changes a counter kept outside the function.
Let n be a counter stored outside both functions, starting at 0. Define:
f(x)returnsx + 1.g(x)adds 1 ton, then returnsx + n.
-
Call
fwith 5. It computes and returns 6. Nothing outside the function changed. Check: call it again with 5 and you get 6 again. -
Call
gwith 5 the first time. It adds 1 ton, sonbecomes 1. It returns . Check: the result is 6, andnhas changed from 0 to 1. That change is the side effect. -
Call
gwith 5 the second time. It adds 1 ton, sonbecomes 2. It returns . Check: the same input gave a different output, because the function read a value it did not receive as input. -
Count what you need to know. To predict
f(5), you need only the number 5. To predictg(5), you need the number 5 and the current value ofn, and you must also account for the changegmakes. Check:fcan be replaced by its answer anywhere.gcannot, because the answer changes with the history of calls.
flowchart LR X["Input 5"] --> G["g runs"] N["Outside value n"] --> G G --> R["Returns 6 then 7"] G --> W["Writes n back: the side effect"]
Step 3 is the one to remember. The function's output depends on something outside its inputs, and the call changes that outside thing, so the next call starts from a different place.
The math
Write a function of its inputs as . A pure function has this form: its output depends only on its input, and the call changes nothing else.
With a side effect, the function also reads and writes a state outside itself. Write the call as a pair of maps:
Here is the returned output, is the state before the call, and is the state after. The side effect is the change from to . If for every and , there is no side effect.
Step 2 in symbols: the counter
For g, the output and the state change are
with the value of n before the call. Starting at and calling with gives and , as in the walkthrough.
Step 3 in symbols: the same input, different output
The second call starts with , so and . Because depends on , the pair is not enough to know the function's behaviour. The input 5 is not a complete description of the call.
Step 4 in symbols: replacing a call by its value
For a pure , if , then everywhere in the program. This substitution is safe, and it is called referential transparency. For , substitution fails: is , not . The side effect means each call must be run in its place in the order of the program.
Worked examples
Consider h(x) which computes and also sets a global variable last to x. Call h(4), then h(4) again.
- The first call computes and returns 8. It sets
lastto 4. - The second call computes and returns 8. It sets
lastto 4 again. - Both calls return 8, so the result did not change.
- The variable
lastchanged from its old value to 4 on the first call, and stayed at 4 on the second. The write tolastis the side effect.
Interpretation: a side effect can be invisible in the return value and still matter. Anything that reads last later sees the effect of the call, even though the call's output is the same.
Let total(items) add up the prices in a list and also write one line to a log file for each item it adds. Let the prices be [3, 5, 2]. Think of a log file as a notebook that keeps every line ever written to it.
- For the first item, the function adds 3 to a running sum, and writes one log line. The sum is 3.
- For the second item, it adds 5, making the sum , and writes a log line. The sum is 8.
- For the third item, it adds 2, making the sum , and writes a log line. The sum is 10.
- The function returns 10. The log file now has three lines.
- A unit test that checks only the return value passes, and the log file is never checked. Running the function a second time on the same list returns 10 again and adds three more lines.
Interpretation: the return value is the same each time, but the program's history is different after each call. Testing must check the side effects as well as the output, or it will miss a file that grows without limit.
A checkout function charges a card for 40 dollars and sends a receipt email. The payment network does not reply in time, so the program does not know whether the charge succeeded, and it retries the whole function.
- The first attempt sends the charge request. The network charges the card, but the reply is lost.
- The program sees a timeout and calls the function again.
- The second attempt sends another charge request for 40 dollars.
- The customer is charged a total of 40 + 40 = 80 dollars, and two receipt emails are sent.
- The fix is to attach a unique key to the charge, so the network recognises the second request as a repeat of the first and returns the first result without charging again.
Interpretation: a function with side effects is not safe to retry unless the effect itself is designed to be repeatable. Keeping the decision, the charge and the email in separate steps makes each one easier to guard.
Try it: A function adds 1 to a counter outside itself and returns the counter's new value. The counter starts at 0. What do three calls return, in order?
Answer: The first call sets the counter to 1 and returns 1. The second sets it to 2 and returns 2. The third sets it to 3 and returns 3. The answers are 1, 2 and 3.
Common mistakes and tradeoffs
It is tempting to think that a side effect is always a bug. In fact side effects are how a program does useful work. A program with no side effects can compute an answer but cannot save it, show it, or send it. The goal is to know where the effects happen, not to remove them everywhere.
It is tempting to think that a function with no visible output has no effect. In fact a function that returns nothing exists only for its side effect, such as writing a file or updating a screen. Its work is the change it makes, so reading only its return value tells you nothing.
It is tempting to think that a side effect is only a change to a variable. In fact reading the clock, reading a file, asking a random number generator, and waiting on a network all depend on the outside world. A function that does any of these is impure, even if it writes nothing, because the same inputs may return different results later.
When to use side effects: the purpose of the code is to change something outside, such as saving a file or sending a message, or the speed gain from changing shared state is large. When to avoid them: the code is a calculation that should be tested, repeated or run in parallel. Alternatives: keep the calculation pure, return a description of the change, and perform the change in one small place at the edge of the program. In Haskell, a monad such as IO is one way to describe an effect as a value before running it, and keeping data immutable removes many of the shared-state effects in the first place. This is the main idea of Functional Programming, and it is why many programs separate their logic from their input and output code.
History
Early programming languages in the 1950s treated a subroutine as a sequence of instructions that could change anything in memory. Side effects were the normal way to communicate between parts of a program, because the machine was built around shared memory.
The idea of a function that returns only a value, with no hidden effects, came from mathematics, from work such as the lambda calculus, and was made practical in functional languages such as Lisp and the ML family in the 1960s and 1970s. Those languages showed that pure code is easier to reason about, though they still allowed effects where needed.
Side effects became a central design question as programs grew, sent data over distributed systems and ran many threads at once. Programmers learned that repeated effects, such as a charge sent twice, cause real harm, and that concurrent effects need coordination. This made separating pure logic from effectful code a common practice.
Recap
- A side effect is anything a function does besides returning its result, such as changing shared state, writing a file or sending a message.
- A function with side effects depends on more than its inputs, so the same input can give different outputs.
- A pure function can be replaced by its value anywhere, but a call with side effects must run in its place in the order of the program.
- Side effects are needed for useful work, but a repeated side effect can cause harm, as in a double charge.
- A common design is to keep calculations pure and perform side effects in a few places at the edge of the program.
Read next: Pure Function for the case with no side effects, Mutable State for the most common kind, and Functional Programming for a style that moves effects to the edges of a program.
Check yourself
QuestionWhat is a side effect, in one sentence?Show answer
A side effect is any change a function makes outside its return value, such as changing shared state, writing a file, printing a line or sending a message.
QuestionA function returns the input times 3 and also increments a counter outside itself. The counter starts at 10. What does the function return on the call with input 2, and what is the counter afterwards?Show answer
The function returns , and the counter becomes . The return value depends only on the input, but the counter change is the side effect.
QuestionWhy can a function with a side effect be unsafe to retry?Show answer
Each run repeats the effect. If the first run already changed the outside world, such as charging a card, a retry changes it again, so the total effect is doubled. A retry is safe only when the effect is repeatable, for example when a unique key lets the other side ignore the repeat.
QuestionA pure function f has f(3) = 4. Why can the program replace f(3) + f(3) with 8, but not do the same for a function with a side effect?Show answer
For a pure function the output depends only on the input, so every call with 3 gives 4 and the substitution is always correct. For a function with a side effect the output can change between calls because the state changes, so each call must be run in order and cannot be swapped for a fixed value.
Sources
- "Side effect (computer science)", Wikipedia: https://en.wikipedia.org/wiki/Side_effect_(computer_science)
- "Pure function", Wikipedia: https://en.wikipedia.org/wiki/Pure_function
- "Referential transparency", Wikipedia: https://en.wikipedia.org/wiki/Referential_transparency