Skip to content

Pure Decisions & Effects

The Course
•
20 min study

A reliable application separates deciding what should happen from making it happen. A pure function derives a result from explicit inputs without changing external state. This makes the decision easy to repeat and test, while an outer layer owns storage and presentation.

Understand the contract

The example proposes a new balance rather than modifying an account object. Same inputs produce the same result; no clock, random value or global variable is read. Invalid requests throw before a new value is returned. Returning a value does not by itself make code pure: a method could still mutate a list it receives, so document and preserve ownership.

An effect is an observable action such as updating storage, printing output or sending a request. Main can perform an effect after the decision succeeds. That order matters: subtracting from a stored balance and only then checking whether it became negative can leave broken state even when an exception is thrown.

Keep business decisions small and explicit. Pure core does not mean every line must use streams or that all mutable variables are forbidden. A local accumulator inside a method is compatible with a pure external contract. The question is what a caller can observe beyond the returned result or documented failure.

Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.

Predict, then run Java
public class Main {
    public static void main(String[] args) {
        int original = 10;
        int proposed = reserve(original, 3);
        System.out.println(proposed);
        System.out.println(original);
    }

    static int reserve(int available, int requested) {
        if (available < 0 || requested <= 0 || requested > available) {
            throw new IllegalArgumentException("invalid reservation");
        }
        return available - requested;
    }
}
Check your prediction
Text
7
10

Trace a different case

The int example above could never show an impure method: Java copies an int argument, so nothing reserve does can change the caller's original. A Map argument is different. The caller and the method share one map object. Below, two methods enforce the same rule on the same map. One changes the map and then checks; the other checks first and returns a new map. Predict both lines.

Mutate, then validate Java
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> first = new LinkedHashMap<>();
        first.put("A", 10);
        try {
            reserveInPlace(first, "A", 11);
        } catch (IllegalArgumentException expected) {
            System.out.println("In place rejected: " + first);
        }

        Map<String, Integer> second = new LinkedHashMap<>();
        second.put("A", 10);
        try {
            second = reserve(second, "A", 11);
        } catch (IllegalArgumentException expected) {
            System.out.println("Pure rejected: " + second);
        }
    }

    static void reserveInPlace(Map<String, Integer> stock, String id, int quantity) {
        stock.put(id, stock.get(id) - quantity);
        if (stock.get(id) < 0) {
            throw new IllegalArgumentException("not enough " + id);
        }
    }

    static Map<String, Integer> reserve(Map<String, Integer> stock, String id, int quantity) {
        int left = stock.get(id) - quantity;
        if (left < 0) {
            throw new IllegalArgumentException("not enough " + id);
        }
        Map<String, Integer> result = new LinkedHashMap<>(stock);
        result.put(id, left);
        return result;
    }
}
Check your prediction
Text
In place rejected: {A=-1}
Pure rejected: {A=10}

Both methods threw, so both callers saw "rejected". Only one left the stock in a valid state. reserveInPlace wrote -1 into the caller's map before its check ran, and the exception did not undo the write. reserve never touches its argument. It returns the new state, and the caller's assignment second = reserve(...) is the only commit; it is skipped when the call throws. A test that only checks "was it rejected?" passes for both versions. A test that inspects the map afterward tells them apart.

Define what the caller can observe

A local accumulator can change during a pure calculation without changing anything outside the call. In contrast, editing a caller's list or updating a shared counter is an externally visible effect. Do not classify code as pure merely because it returns a value or uses streams.

For a proposed balance, take a before value, calculate the result, then decide where the caller commits it. An exception during the decision should prevent that commit. The same principle extends to a staged collection on the next page.

Test repeated calls with the same inputs and inspect any shared arguments afterward. Deterministic results and preserved input are separate observations. Moving presentation outside the calculation also prevents repeated tests or retries from printing receipts or other effects unintentionally.

Build it yourself

Exercise

Pure Decisions & Effects: practice

Write checkout(Map<String, Integer> stock, List<String> cart). Each ID in the cart takes one unit. Return a new map with the reduced counts, and throw IllegalArgumentException for an unknown ID or an item that has run out. The caller's map must never change, whether the call succeeds or fails.

Write tests that can fail. Starting from {A=2, B=1}:

CaseExpected
cart [A, B]returns {A=1, B=0}
after that callstock is still {A=2, B=1}
the same call againthe same result
empty carta map equal to stock
cart [A, A, A]rejected; stock still {A=2, B=1}
cart [C]rejected

Print Checkout checks passed. Then prove your tests can fail: change checkout to work on stock directly, run them, and note which check fails first.

Your workspace Java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Build the stock map, take a snapshot, then check each table row.
        System.out.println("Your workspace");
    }

    static Map<String, Integer> checkout(Map<String, Integer> stock, List<String> cart) {
        // Copy first; validate and update only the copy.
        return new LinkedHashMap<>(stock);
    }
}
Hint 1: the idea

Purity is about what the caller can observe afterward. To test it, keep a snapshot of the argument from before the call and compare after. A test that looks only at the return value cannot see a changed argument.

Hint 2: a first step

Make before with new LinkedHashMap<>(stock) at the start of main. Inside checkout, make the copy on the first line and let every get and put use the copy. Write a small rejects helper that expects the exception.

Show one solution
Java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new LinkedHashMap<>();
        stock.put("A", 2);
        stock.put("B", 1);
        Map<String, Integer> before = new LinkedHashMap<>(stock);

        Map<String, Integer> after = checkout(stock, List.of("A", "B"));
        check("result", after.equals(Map.of("A", 1, "B", 0)));
        check("argument after success", stock.equals(before));
        check("repeatable", checkout(stock, List.of("A", "B")).equals(after));
        check("empty cart", checkout(stock, List.of()).equals(stock));

        rejects(stock, List.of("A", "A", "A"));
        rejects(stock, List.of("C"));
        check("argument after rejection", stock.equals(before));
        System.out.println("Checkout checks passed");
    }

    static Map<String, Integer> checkout(Map<String, Integer> stock, List<String> cart) {
        Map<String, Integer> result = new LinkedHashMap<>(stock);
        for (String id : cart) {
            Integer count = result.get(id);
            if (count == null) {
                throw new IllegalArgumentException("unknown " + id);
            }
            if (count == 0) {
                throw new IllegalArgumentException("out of " + id);
            }
            result.put(id, count - 1);
        }
        return result;
    }

    static void rejects(Map<String, Integer> stock, List<String> cart) {
        try {
            checkout(stock, cart);
            throw new AssertionError("accepted " + cart);
        } catch (IllegalArgumentException expected) {
            // The documented rejection.
        }
    }

    static void check(String name, boolean condition) {
        if (!condition) {
            throw new AssertionError(name);
        }
    }
}

Expected output:

Text
Checkout checks passed

The copy is made before the loop, so a cart that fails on its third item has only changed a map nobody else can see. The "argument after success" check is the one that catches an in-place version: with result = stock, the first call returns the right counts but has already reduced the caller's map, and the run stops with AssertionError: argument after success. "repeatable" makes the same point from the other side: an impure version would return {A=0, B=-1}, or throw, on its second call.

Change it and test again

Add a cart with a duplicate that exactly uses up stock, such as [B] from {B=1} then [B, B]. Imagine the function also prints a receipt: repeated tests now create output, and retrying the decision could print twice. Move that printing to a caller. Keep error messages useful while avoiding an exception catch that turns every programming error into an ordinary rejected request.

Explain before moving on

Which part can be tested without constructing a store? Which line commits a decision? Explain why testing only the returned number would miss an unintended change to an input collection or external counter.

Was this article helpful?

Your response is saved on this device.