Workbench / Volume 3 Companion: The Backend
V3·37
Functional Programming
Companion to Volume 3, chapter 37: how functions as values, pure functions, streams, Optional and monads connect; new angles (a pure function as a recipe card, a stream as an order ticket that is cooked only when the pass calls it, a clock read inside a function as an ingredient bought at a different shop each time); what the chapter simplifies, measured on JDK 21 and the build's stage 38: a review page that priced an order at the real time while the receipt priced it at the server's, Optional failing the laws the chapter says monads keep, a stream that saw changes made after it was created, and a listener that couldn't be removed because two method references are two objects; the theory behind referential transparency; how ArrayList's spliterator binds late; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 37 has four parts: first principles (functions as values, purity, immutability, map, filter and fold), functions as values in Java (functional interfaces, lambdas and closures, method references, composition), streams (laziness, flatMap, collectors, Optional and monads) and side effects, parallelism and performance (pipelines with effects, parallel streams, pitfalls, recursion, a functional core in a Spring service).
The links worth remembering:
- Purity is a property of the inputs as much as the code. A function that reads the clock, a static, a system property or a mutable field has an input its signature doesn't show. Make it a parameter, and the function becomes testable at any value of it.
- Laziness moves work, and its effects, to the terminal operation. Whatever a pipeline does happens when, if and as often as the terminal operation decides. Side effects in it inherit that timing.
- Composition needs laws. Splitting a
mapinto two, or fusing two into one, is safe only if the pieces obey the identity and composition laws. Java'sOptionaldoesn't quite, because ofnull.
Explain it differently
1. A pure function is a recipe card. Given the same ingredients, it produces the same dish, and following it changes nothing in the kitchen except the dish. You can follow it twice to check, hand it to another cook, or cook ten copies at once.
2. Reading the clock inside a function is buying an ingredient at a different shop each time. The card says "add today's vegetables". Two cooks following it an hour apart make different dishes, and nobody can test the recipe with a known batch. Stage 38's review page did this: it priced the order with the vegetables of the moment, while checkout used the kitchen's own delivery.
3. A stream is an order ticket, not a cooked dish. Writing orders.stream().map(...) writes the ticket. Nothing is cooked until the pass calls it (the terminal operation), and the cook uses what's in the fridge then, not what was there when the ticket was written (Gaps 3).
4. A collector is one bowl per cook. In parallel, each cook fills their own bowl and the bowls are tipped together at the end. A forEach into a shared list is every cook throwing food at one bowl from across the room.
5. Optional is a lunchbox that might be empty. map is "if there's food, do this to it, and put the result back in a lunchbox". flatMap is for a step that hands you its own lunchbox, so you don't end up with a box inside a box. Java's lunchbox has a quirk: if the step returns nothing at all (null), you get an empty box, not a box holding nothing (Gaps 2).
6. A method reference is a phone number written on a new card each time. this::onOrder written twice is two cards with the same number. Ask the receptionist to remove "this card" from the call list and they'll say it was never on it (Gaps 4).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from OpenJDK 21.0.12 and the build's stage 38 (exp/38), unless stated.
1. A function that calls Instant.now() isn't pure, even if it changes nothing. The chapter defines purity as "the result depends only on the arguments" and shows a Spring service with an injected Clock. It doesn't say how easy it is to miss one call. TiffinBox's server took its clock from the caller, and every rule saw the time through Facts. But the review page built its preview order with Instant.now(). With the server's clock fixed at 08:00 in Chennai and a rule "Breakfast when hour < 11 then ₹20 off":
server clock: 08:00 in Chennai
real clock: 19:45:24 in Chennai
review page: To pay ₹179.00
receipt: Total ₹179.00, discount ₹20.00, to pay ₹159.00.
The rule engine was pure; its input wasn't. In production the two clocks agree (to the millisecond), so the bug only shows under a test clock, a replay, or a time-travel debugging session, which are exactly the situations a clock is injected for. A compiler check that bans the ambient clock outside the program's entry point found it, and three other places (Code walkthrough's experiment and stage 38).
2. Optional doesn't keep the laws the chapter says monads keep. The chapter says monads come with "laws (associativity and identity) guaranteeing that chaining behaves predictably however you group it". Java's Optional.map turns a null result into empty. So splitting or fusing a chain changes its meaning when a step returns null:
c1: map(f).map(g).map(h) = ships to Chennai map(f.andThen(g).andThen(h)) = ships to Chennai
c2: map(f).map(g).map(h) = (empty) map(f.andThen(g).andThen(h)) = city unknown
c9: map(f).map(g).map(h) = (empty) map(f.andThen(g).andThen(h)) = NullPointerException
f(null) throws NullPointerException
Optional.of(null) throws NullPointerException
Optional.ofNullable(null).flatMap(f) = Optional.empty
f looks up a customer (it may return null), g reads the city (it may be null) and h labels it, handling null itself. Chained, a null from f or g short-circuits to empty and h never runs; composed, h sees the null (c2), or g is called on a missing customer and throws (c9). That is the composition law failing: map(f).map(g) should equal map(f.andThen(g)). Left identity fails too: Optional.of(x) refuses null, and ofNullable(null).flatMap(f) isn't f(null). The practical rule: functions passed to Optional.map must never return null if you might regroup the chain; return Optional and use flatMap, or keep null out of the domain (records that validate). Rust's Option and Haskell's Maybe keep the laws because they have no null.
3. A stream reads its source when the terminal operation runs, not when it's created. The chapter says streams are lazy and that the source mustn't be modified during the pipeline. What happens between creating the stream and running it depends on the source:
ArrayList, changed before the terminal op: [DOSA, VADA, PONGAL]
ArrayList, changed during the terminal op: ConcurrentModificationException
CopyOnWriteArrayList, changed before the terminal op: [dosa, idli, vada]
array, changed before the terminal op: sum = 105
HashMap.keySet, changed before the terminal op: [dosa, vada]
ArrayList, arrays and HashMap views are late-binding: the stream sees the source as it is when the terminal operation starts (pongal added, idli removed, arr[0] = 100). CopyOnWriteArrayList snapshots its array when the stream is created. So a method that returns orders.stream().filter(...) instead of a list hands out a view whose contents depend on when the caller consumes it, and on what happened in between. Return a list (toList()) when the result must describe "now".
4. Two method references to the same method are two objects. The chapter's table treats this::validate as shorthand for a lambda. It doesn't say what that means for identity, which matters for anything that removes callbacks:
after open() and close(): 1 listener(s) still subscribed
the closed screen still counted 1 order(s)
s::onOrder == s::onOrder: false, equals: false
Refs::log == Refs::log (two places in the code): false
Refs::log from one place, evaluated twice: true
s::onOrder from one place, evaluated twice: false
keeping the reference: 0 listener(s) after unsubscribe
subscribe(this::onOrder) and unsubscribe(this::onOrder) create two objects, and lambdas don't override equals, so List.remove finds nothing and the closed screen keeps receiving events (and stays reachable: a memory leak). The rules are an implementation detail: HotSpot reuses one instance for a non-capturing lambda at one place in the code, and creates a new one for each evaluation of a capturing one (s::onOrder captures s). The specification promises neither. Keep the object you subscribed, or have subscribe return a handle (AutoCloseable) that unsubscribes.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "No mutation means pure." | Reading the clock, a static or a system property is a hidden input. | Gaps 1; stage 38 |
"Optional is a monad, so chains can be regrouped." |
Not when a mapped function returns null. |
Gaps 2 |
| "A stream is a snapshot of its source." | Most sources bind when the terminal operation starts. | Gaps 3 |
"A ConcurrentModificationException stops the pipeline before damage." |
ArrayList's forEach checks once, at the end: every element was processed. |
Code walkthrough |
"this::m is a value; equal values are equal." |
Each evaluation may be a new object, and there's no equals. |
Gaps 4 |
| "Parallel streams make pure code faster." | Only for large, CPU-bound, splittable work. | the chapter's lab, Experiment 3 |
"Side effects in map run once per element." |
They run when, whether and as often as the terminal operation pulls. | the chapter's lab, Experiment 4 |
Theoretical gaps: the ideas behind the chapter
1. Referential transparency. An expression is referentially transparent if replacing it with its value never changes the program (Quine's term, brought to programming by Strachey in 1967). It's what makes equational reasoning (rewriting code like algebra) sound. Instant.now() isn't: two occurrences can't be merged into one variable without changing behaviour.
2. Functor and monad laws. A functor's map must keep identity (map(x -> x) changes nothing) and composition (map(f).map(g) = map(g ∘ f)). A monad adds unit and flatMap with left identity, right identity and associativity. Laws are what make refactorings valid; Gaps 2 shows where Java's Optional breaks them. Wadler's "Monads for functional programming" (1995) is the readable introduction.
3. Effects as data. Instead of performing an effect, a pure function can return a description of it (a list of events to publish, a command to run), which the shell executes. Haskell's IO, the "free monad" pattern and Elm's architecture work this way; the chapter's "functional core, imperative shell" is the everyday version.
4. Strict, lazy and call-by-need. Strict evaluation computes arguments before a call; lazy computes them when needed; call-by-need computes them at most once (Haskell). Java streams are lazy in their intermediate operations; Supplier is call-by-name (recomputed each get) unless memoised.
5. Defunctionalisation and closure conversion. A lambda is compiled to an object holding its captured variables plus code (Reynolds, 1972, showed functions can be replaced by data plus an apply). In Java, invokedynamic and LambdaMetafactory create that object at run time, which is why capturing lambdas allocate and why identity is unspecified (Gaps 4).
Applying it
Code walkthrough
Gaps 3 comes from how ArrayList creates the spliterator a stream reads from. From openjdk/jdk21u, src/java.base/share/classes/java/util/ArrayList.java.
Creating the spliterator: nothing is read yet
public Spliterator<E> spliterator() {
return new ArrayListSpliterator(0, -1, 0);
}
private int index; // current index, modified on advance/split
private int fence; // -1 until used; then one past last index
private int expectedModCount; // initialized when fence set
private int getFence() { // initialize fence to size on first use
int hi; // (a specialized variant appears in method forEach)
if ((hi = fence) < 0) {
expectedModCount = modCount;
hi = fence = size;
}
return hi;
}
list.stream() builds a spliterator with fence = -1: "I don't know where the list ends yet". The size and the modification count (modCount, incremented by every structural change) are read on first use. That's the late binding Gaps 3 measured: elements added before the terminal operation are seen, because nobody looked at the list until then.
Walking it: one check, at the end
public void forEachRemaining(Consumer<? super E> action) {
int i, hi, mc; // hoist accesses and checks from loop
Object[] a;
if (action == null)
throw new NullPointerException();
if ((a = elementData) != null) {
if ((hi = fence) < 0) {
mc = modCount;
hi = size;
}
else
mc = expectedModCount;
if ((i = index) >= 0 && (index = hi) <= a.length) {
for (; i < hi; ++i) {
@SuppressWarnings("unchecked") E e = (E) a[i];
action.accept(e);
}
if (modCount == mc)
return;
}
}
throw new ConcurrentModificationException();
}
The fast path (used by forEach and most terminal operations without short-circuiting) copies the array reference, size and count into locals, runs the action on every element with no checks inside the loop, and compares the count once at the end. The comment above the class says why: "we can normally only detect interference after actions, not before".
Stepping: a check after each element
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
int hi = getFence(), i = index;
if (i < hi) {
index = i + 1;
@SuppressWarnings("unchecked") E e = (E)elementData[i];
action.accept(e);
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
Short-circuiting operations (findFirst, anyMatch, limit) pull one element at a time through tryAdvance, which checks after every element. CopyOnWriteArrayList.spliterator() is simpler: it wraps the current array, which no writer ever changes (writers copy it), so the stream is a snapshot and never throws.
Debugging drills
D1. A test that passes in the morning
A pricing test passes when the team runs it in India in the morning and fails in the afternoon. CI, in UTC, fails on Mondays only. The test fixes the service's Clock to a Tuesday at 09:00.
D2. A screen that keeps counting after it closes
A dashboard component subscribes with bus.subscribe(this::onEvent) when opened and unsubscribes with bus.unsubscribe(this::onEvent) when closed. After a day, the server's heap holds 40,000 closed dashboards, and each event is handled 40,000 times.
D3. A report that includes orders placed after it was generated
A nightly report method returns Stream<Order> from orders.values().stream().filter(o -> o.date().equals(day)), and the caller writes it to a file a few seconds later. Some reports contain orders placed after midnight, and one run failed with a ConcurrentModificationException.
D4. A refactoring that broke "unknown city"
A developer replaced customer.map(Customer::address).map(Address::city).map(this::label) with customer.map(c -> label(c.address().city())) "to avoid three allocations". Customers without an address now cause NullPointerExceptions, and customers with an address but no city get "unknown city" instead of nothing.
Career-oriented
Interview prep
Mid-level 1: what makes a function pure
Question. "Is this pure: boolean isLunchTime() { return LocalTime.now().getHour() >= 12 && LocalTime.now().getHour() < 15; }? How would you test it?"
How to get there. Inputs you can see, inputs you can't, then the test.
Mid-level 2: map against flatMap
Question. "findCustomer(id) returns Optional<Customer>, and Customer.defaultAddress() returns Optional<Address>. Get the city, or "unknown"."
How to get there. What each step returns, then which operator keeps one level of box.
Senior 1: a functional core in an existing service
Question. "Our checkout service mixes database calls, pricing and email in one 300-line method. How would you make the pricing testable without mocks?"
How to get there. Find the decisions, find their inputs, move the I/O out.
Senior 2: parallel streams in a web service
Question. "A colleague added .parallel() to a stream that calls a pricing service for each of 200 order lines, and latency got worse under load. Why, and what should they do?"
How to get there. Where the threads come from, what the work is, what the server is already doing.
Staff 1: adopting functional style across teams
Question. "Half the teams love streams and Optional; the other half find the code unreadable. What do you do?"
How to get there. What the disagreement is really about, then rules with reasons, then tooling.
Staff 2: time as an input, across a platform
Question. "Several incidents came from code reading the system clock: a billing job that ran twice across a DST change, tests that fail at midnight, a replay tool that gave different results from production. Propose a platform-wide fix."
How to get there. Where time enters, how it flows, how to enforce it.