Volume 1 Companion: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Companion: Foundations of Computing

V1·02

Programming Fundamentals & Paradigms

Companion to Volume 1, chapter 02: how values, control, structure and paradigms connect; the chapter from new angles (two models of a variable, types as units of measurement, the waiter who reports a problem four ways); what it simplifies, from Java finals that reflection changes to switches that fall through, and the theory behind it (call by sharing, Liskov substitution, Curry–Howard, undefined behaviour that travels back in time); JDK source for the Integer cache, fail-fast iterators and String's cached hash; four debugging drills; interview questions with how to approach each.

6 sections · ~23 min to read
Updated Suggest a correction

Understanding it better

Concept map

Chapter 02 has three strands that the rest of the book keeps pulling on. Data: what a value is, what a name holds, and who may change it. Control: how code decides, repeats and calls. Structure and safety: how code is split up, reused and kept correct. The bottom row holds the cross-cutting ideas, the lenses through which you choose between all of the above.

data control structure and safety values and types bits + an interpretation variables a name bound to storage value vs reference what assignment copies compound data arrays · records · sum types immutability, ownership who may change what expressions, operators precedence · conversions control flow if · match · loops · jumps functions and frames parameters · locals · return closures, higher-order functions as values recursion and the stack base case · depth limit modules, visibility what callers can see abstraction, polymorphism interfaces · dispatch generics templates · erasure · monomorph. error models exceptions · values · Result testing and debugging examples · properties · UB type systems static · dynamic · structural paradigms imperative · OO · functional I/O and serialization bytes cross a boundary named by assignment copies safe to share if decide with as values hide the how reuse over types found by args copy dispatch enforced by functional style test the edges goes deeper: ch3 data structures · ch4 recursion and algorithms · ch6 representation · ch10 runtimes and GC Volume 3, ch 33–37: Java language, OOP, collections, generics, functional style
Concept map of chapter 02: data (values and types, variables, value and reference semantics, compound data, immutability and ownership), control (expressions, control flow, functions and frames, closures and higher-order functions, recursion and the stack), structure and safety (modules, abstraction and polymorphism, generics, error models, testing), and the cross-cutting ideas of paradigms, type systems, and I/O with serialization.

The links that matter most later:

  • "What does assignment copy?" decides most bugs in this chapter. Value against reference semantics explains aliasing, defensive copies, closures capturing variables, and why immutability makes sharing safe. When behaviour surprises you, ask that question first.
  • Functions are where data meets control. Arguments copy values (or references), each call gets a frame, and closures keep variables alive after the frame is gone. Recursion is just functions calling themselves, so the stack limit is a data-structure limit.
  • Type systems and error models are two halves of one question: which mistakes are stopped before the program runs, and how the rest are reported when it does?

Explain it differently

1. Two models of a variable: a box, or a name tag. The chapter calls a variable a "labelled box". That's exactly right for C and Java primitives, and misleading for Python, Java objects and JavaScript, where a variable is a name tag tied to a value that lives elsewhere. Run both and watch the difference (real output):

C
int a = 120;
int b = a;      /* copies the value into a second box */
b = b + 30;
printf("a=%d b=%d, a lives at %p, b lives at %p\n", a, b, (void*)&a, (void*)&b);
Terminal
a=120 b=150, a lives at 0x7ffc0382c7a0, b lives at 0x7ffc0382c7a4

Two boxes, four bytes apart, each holding its own number. Now Python:

Python
a = [120, 80]
b = a                      # tie a second tag to the same list
b.append(150)              # change the list through tag b
b = [1]                    # move tag b to a new list
Terminal
a is b: True | same id: True
a after b.append(150): [120, 80, 150]
a after b = [1]: [120, 80, 150] | a is b: False

b.append changed the one list both tags were tied to. b = [1] moved tag b; it didn't touch the list. Once you see variables as tags, three rules of the chapter collapse into one:

  • assignment never copies an object;
  • mutation is visible through every tag on the object;
  • re-assignment affects only the tag you moved.

Java objects behave like Python here, and Java primitives like C.

2. Types are units of measurement. In physics, you can't add 3 metres to 5 seconds, and checking units catches whole classes of mistakes before any calculation (dimensional analysis). A type system is dimensional analysis for programs. The cost of skipping it is real: NASA's Mars Climate Orbiter was lost in 1999 because one team's software produced thrust impulse in pound-force seconds and another's expected newton-seconds. Both values were plain doubles, so nothing could object. In TiffinBox, a long that might be paise or rupees is that bug waiting to happen. A Money type (the TiffinBox build, stage 2) is a unit the compiler checks.

3. A call stack is a hotel where every call takes the next floor up. Each call checks in to a new floor (its frame) with its luggage (parameters and locals), does its work, and checks out, freeing the floor. A function that calls itself books the next floor up. The building has a fixed height (the thread's stack size), so a recursion that never reaches its base case runs out of floors: a stack overflow. Tail-call optimisation is the hotel letting you stay on your floor when your only remaining job is to send the guest upstairs.

4. A closure is a function with a backpack. When a function is created inside another, it packs the variables it uses from its surroundings into a backpack and carries them wherever it goes, even after the place it was made has gone. The chapter's warning about closures that capture the wrong thing is a question of what's in the backpack: a copy of the value at packing time (Java's effectively-final rule, C++ capture by value), or the variable itself, which keeps changing (Python, JavaScript var, Go before 1.22; see drill D1).

5. Four ways for a waiter to report a problem. You order a dish the kitchen can't make. The waiter can:

  • Shout across the restaurant (an exception): whoever is responsible must deal with it, or the whole meal stops. Hard to miss, easy to handle in the wrong place.
  • Write a note on the plate (an error value: Go's err, C's return codes): nothing stops you eating the wrong thing if you don't read the note.
  • Hand you a sealed envelope that you must open to get your food (a result type: Rust's Result, Java's Optional, a sealed outcome type): you can't reach the dish without looking at whether it's there.
  • Refuse to take the order at all (a type error): the menu doesn't list it, so it can never be ordered.

Good systems use all four: types to make impossible orders unorderable, envelopes for expected outcomes ("sold out"), notes where performance matters, and shouts for genuine surprises.

6. Paradigms are ways of giving directions. To get a friend from Secunderabad station to Charminar:

  • Imperative: "turn left, walk 200 m, take the second right…" (step by step, changing your position as you go).
  • Declarative: "take me to Charminar" (say what you want and let the driver plan).
  • Functional: a pipeline of transformations: station → road → bridge → old city → Charminar, each step taking a place and returning a place, nothing changed in between.
  • Object-oriented: "ring the auto stand; they know the routes": ask an object that owns the knowledge.
  • Logic: "find me any route that's under 30 minutes and avoids the Tank Bund jam": state constraints and let the system search.

None is "the right way". Each makes some directions short and others long, which is why the chapter's languages mix them.

7. Polymorphism is a power socket. A socket defines a shape (an interface). A kettle, a phone charger and a mixer-grinder all fit, and the socket neither knows nor cares what's plugged in. That's all polymorphism is: code written against the socket works with anything that fits it. Generics are a socket with an adaptor slot ("a list of something"). Dynamic dispatch is the electricity flowing to whichever appliance is plugged in at the moment.

8. Ownership is a library book. Rust's rules map onto a library: one owner holds the book; you can lend it to many people to read at once (shared borrows), or to exactly one person to write notes in (a mutable borrow), but never both at the same time; and a borrower must return it before the owner gives it away (lifetimes). Java and Python run the library differently: everyone holds a photocopy of the call number (a reference), anyone can write in the book, and a librarian (the garbage collector) shelves books nobody refers to any more.

Gaps and misconceptions

What the chapter oversimplifies

1. "A constant is a variable you promise never to change; the compiler holds you to the promise." The compiler holds you to it at compile time. At run time, Java's reflection can change a final instance field, and whether your code sees the change depends on something the chapter doesn't mention: whether the field is a compile-time constant. Real output (JDK 21):

Java
public class Arr {
    static final String CITY = "Hyderabad";
    final String kitchen = "k7";
    String label() { return kitchen; }
    ...
        Field f = Arr.class.getDeclaredField("kitchen"); f.setAccessible(true); f.set(o, "k9");
        System.out.println("final field after reflection: field=" + f.get(o) + " label()=" + o.label());
        Field s = Arr.class.getDeclaredField("CITY"); s.setAccessible(true);
        try { s.set(null, "Pune"); } catch (Exception e) { System.out.println("static final: " + ...); }
Terminal
final field after reflection: field=k9 label()=k7
static final: IllegalAccessException: Can not set static final java.lang.String field Arr.CITY to java.lang.String

Reflection changed the field to k9, yet label() still returned k7. A final field initialised with a constant expression is a compile-time constant, so javac copied "k7" into label() instead of reading the field. static final fields are refused outright. So final is a strong promise but not an absolute one. Frameworks (serialisation, dependency injection, mocking) do write final fields through reflection, and compile-time constants are copied into other classes too: change a public static final int in a library without recompiling its callers, and they keep the old value.

2. "Static typing catches type errors before running." Mostly. Java has a famous hole that compiles cleanly and fails at run time, because arrays are covariant (a String[] is an Object[]):

Java
String[] dishes = {"idli", "dosa"};
Object[] things = dishes;            // compiles: arrays are covariant
things[0] = 42;                      // compiles too
Terminal
ArrayStoreException: java.lang.Integer

The type checker accepted the program, so the JVM must check every store into an array of references at run time. Generic collections were designed the other way (a List<String> is not a List<Object>), precisely to close this hole. Static typing guarantees what the language's rules guarantee, and every mainstream language has such holes: casts, reflection, null, erasure (exercise P11), unsafe blocks.

3. "Java: left to right, always" and "by value, always" are true, and still mislead. Java does evaluate left to right, and it does pass everything by value. But "by value" for objects means the reference is copied. The precise name for that is call by sharing (from CLU, 1974): the callee can't rebind the caller's variable, but it can mutate the shared object. Many developers argue "Java is pass-by-reference for objects" for years because nobody gave them the third term. Python, JavaScript, Ruby and Go's slices and maps all use call by sharing too.

4. "Exhaustiveness: when you add a new enum variant, every match that forgot it becomes a compile error." Only for switches that are expressions or use patterns. In Java, the old statement form, switch (s) { case A: …; case B: … }, isn't checked for exhaustiveness at all. It also falls through from one case into the next unless you write break. Real output for "what's on the menu on day 2?":

Java
switch (day) { case 1: plan += "idli "; case 2: plan += "dosa "; case 3: plan += "vada "; default: plan += "closed"; }
String p2 = switch (day) { case 1 -> "idli"; case 2 -> "dosa"; case 3 -> "vada"; default -> "closed"; };
Terminal
old switch, day 2: dosa vada closed
arrow switch, day 2: dosa

javac -Xlint:all does warn ([fallthrough] possible fall-through into case), but only if you turn the warning on. Arrow-form switches neither fall through nor need break, and switch expressions must be exhaustive. Codebases older than Java 14 are full of the other kind.

5. "Strong versus weak typing is a separate axis." The chapter presents it like static against dynamic, as if it were well defined. It isn't: there's no agreed definition of "strongly typed". It's used to mean "few implicit conversions", "no way to reinterpret memory", or just "the language I like". When someone says a language is strongly typed, ask which conversions or loopholes they mean. "Does "5" + 1 work, and what does it give?" is a better question than "is it strong?".

Common misconceptions

Misconception What's actually true Where it's shown
"Java passes objects by reference." It passes references by value (call by sharing). The callee can't make your variable point elsewhere. gap 3 above; Chapter Exercises T10
"final makes an object immutable." It makes the variable unassignable. The object it refers to can still change (a final List can still be added to). chapter, "Immutability"
"Records are immutable." Records are shallowly immutable. A record holding a List is only as immutable as that list (the TiffinBox build, stage 2, copies it). chapter, "Immutability"
"Removing from a list while looping always throws ConcurrentModificationException." Not always: removing the second-to-last element makes the loop end quietly and skip the last element. Code walkthrough below
"== compares values for small numbers, so it's safe for IDs." It compares references. It only looks right for Integer values from −128 to 127, and that range is configurable. Code walkthrough below
"Go's go vet catches loop-variable capture." It flags captures in go and defer statements, but not closures stored for later. drill D1
"Recursion is always slower than a loop." With tail calls optimised, it compiles to the same loop. Without them, it costs a frame per call. Clarity, not speed, usually decides. chapter, "Recursion versus iteration"

Theoretical gaps: the ideas behind the chapter

1. Polymorphism has a correctness rule, not just a mechanism. The chapter explains how polymorphism works (interfaces, dispatch, generics). It doesn't state the rule that makes it safe: the Liskov substitution principle (Barbara Liskov, 1987). Anything true of the supertype must stay true of every subtype, so code written against the interface never gets surprised. A Square extends Rectangle whose setWidth also changes the height type-checks perfectly and breaks every caller that assumed width and height were independent. Type checkers verify the shapes of methods; Liskov is about their behaviour, which only design, contracts and tests can check. (Volume 3, chapter 34; Volume 13.)

2. A type is a claim, and a program is evidence for it. There's a deep correspondence in logic called Curry–Howard: a type is like a proposition, and a value of that type is like a proof of it. A function of type A → B is a proof that "if A, then B". In everyday terms, this is why richer types prevent more bugs:

  • a NonEmptyList<OrderLine> can't be empty, so no code has to check;
  • a sealed OrderStatus can't be in an undefined state;
  • a function that returns Money can't return a negative number if Money's constructor refuses one.

"Make illegal states unrepresentable" (the chapter's sum types section) is Curry–Howard used as an engineering technique. (Chapter 5; the TiffinBox build, stage 2.)

3. Undefined behaviour can travel backwards in time. The chapter explains undefined behaviour as "a promise you make to the compiler: this never happens". The surprising consequence: because the compiler may assume the promise holds, it can change code that runs before the bad operation. If a later line would divide by zero when x is 0, the compiler may conclude x is never 0 and delete an earlier if (x == 0) check entirely. So a C program with UB can misbehave before it reaches the bug, and adding a printf to find the bug can make it vanish. This is why "it worked in debug builds" means nothing for C and C++ code with UB. (Chapter 10; Chapter Exercises P18.)

4. Every recursion can be a loop, and every loop a recursion. The chapter compares recursion and iteration as styles. They're equally expressive: any recursive function can be rewritten as a loop with an explicit stack, and any loop as a tail-recursive function. Functional languages often have no loops at all. So the choice is about clarity and stack limits, never about what can be computed. Turning a deep recursion into a loop with an explicit stack is a standard fix for stack overflows on untrusted input (Chapter Exercises S6).

5. Closures and objects are the same idea seen from two sides. A closure is behaviour carrying some data (its captured variables). An object is data carrying some behaviour (its methods). An object with one method and a closure are interchangeable, which is why Java's lambdas implement single-method interfaces, and why "a closure is a poor man's object, and an object is a poor man's closure" is a well-known programming koan. Choosing between them is choosing which side you want to make easy to extend. (Chapter 2's paradigms section, from the other direction; Volume 3, chapter 37.)

6. Paradigms describe code, not languages. The chapter's paradigm sections are organised around language features, which can suggest that Java is object-oriented and Haskell is functional. Paradigms are styles of organising a solution, and most real code mixes them: a Java service with records, sealed types, pure functions and streams is substantially functional, and a C program with function-pointer tables is object-oriented. When someone asks "is this OO or functional?", the useful answer names which parts use which style, and why.

Applying it

Code walkthrough

Three small pieces of the JDK explain three of this chapter's surprises: why == works on some Integers, why mutating a list while iterating sometimes doesn't fail, and why strings make good map keys. All excerpts are from the jdk-21-ga tag.

Integer.valueOf and the cache: why 127 == 127 but not 128 == 128

java/lang/Integer.java:

Java
    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            ...
            high = h;
            ...
        }
    }

    @IntrinsicCandidate
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

When you write Integer x = 128;, the compiler calls Integer.valueOf(128) (autoboxing). Values from −128 to 127 come from a pre-built array, so two boxes of 127 are the same object and == happens to work. 128 makes a new object each time, so == compares two different objects and fails. Two details the chapter doesn't mention:

  • The upper bound is configurable (-XX:AutoBoxCacheMax), so code that relies on == can pass on one JVM and fail on another:

    Terminal
    $ java It                              # last line of output
    128 == 128 (boxed): false
    $ java -XX:AutoBoxCacheMax=1000 It
    128 == 128 (boxed): true
    
  • The cache is archived with CDS (Class Data Sharing): the comment above the class warns that the cached Integer objects are loaded from a shared archive at startup. That's a hint at how much the JVM cares about this tiny cache: it's touched by nearly every program.

The rule: compare boxed numbers with equals, or unbox them first. Java IDs held as Long are the classic victim.

ArrayList's iterator: fail-fast, but only on a best-effort basis

java/util/ArrayList.java, the iterator used by every for (x : list) loop:

Java
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;
        ...
        public boolean hasNext() {
            return cursor != size;
        }

        public E next() {
            checkForComodification();
            int i = cursor;
            ...
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        ...
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

Every structural change to the list (add, remove) increments modCount. The iterator remembers the value it started with and checks it in next(). Now trace removing during a loop over [idli, dosa, vada]:

  • Remove idli while visiting it: size becomes 2, cursor is 1, hasNext() is true, next() checks modCount and throws.
  • Remove dosa (the second-to-last) while visiting it: size becomes 2, cursor is 2, so hasNext() returns false. next() is never called, nothing is checked, and the loop simply ends, never visiting vada.

Real output:

Terminal
remove idli: ConcurrentModificationException after visiting [idli]
remove dosa: no exception, visited [idli, dosa], menu now [idli, vada]

That's why the ConcurrentModificationException Javadoc says fail-fast behaviour "cannot be guaranteed" and is only for detecting bugs. A loop that "works" in testing may silently skip elements in production. Use removeIf, an explicit Iterator.remove(), or build a new list.

String.hashCode: what immutability buys

java/lang/String.java:

Java
    public int hashCode() {
        // The hash or hashIsZero fields are subject to a benign data race,
        // making it crucial to ensure that any observable result of the
        // calculation in this method stays correct under any possible read of
        // these fields. Necessary restrictions to allow this to be correct
        // without explicit memory fences or similar concurrency primitives is
        // that we can ever only write to one of these two fields for a given
        // String instance, and that the computation is idempotent and derived
        // from immutable state
        int h = hash;
        if (h == 0 && !hashIsZero) {
            h = isLatin1() ? StringLatin1.hashCode(value)
                           : StringUTF16.hashCode(value);
            if (h == 0) {
                hashIsZero = true;
            } else {
                hash = h;
            }
        }
        return h;
    }

This is the chapter's "immutable values can be shared freely" paying off, three times over:

  • The hash is computed once and cached. That's only correct because a String's characters can never change. A mutable key's hash would go stale, which is why mutable objects make dangerous HashMap keys.
  • The cache needs no lock. Two threads may both compute the hash and both write it: a "benign data race". It's safe only because the computation is idempotent and derived from immutable state, exactly as the comment says.
  • hashIsZero exists because 0 is both "not computed yet" and a legitimate hash value (the empty string's, for one). Without the flag, a string whose hash really is 0 would be recomputed on every call, and anyone who can choose your keys can pick such strings. The flag was added in JDK 13 to close that gap.

Read it yourself

  1. In Integer.valueOf, why does cache[i + (-IntegerCache.low)] add 128?
  2. Using the Itr code, predict what happens if you add an element while visiting the last element of a list.

Debugging drills

D1. Go: three closures that print the same dish

Go
dishes := []string{"idli", "dosa", "vada"}
var printers []func()
for _, d := range dishes {
	printers = append(printers, func() { fmt.Print(d, " ") })
}
for _, p := range printers {
	p()
}

On a teammate's machine this prints vada vada vada. On yours it prints idli dosa vada. Same Go toolchain (1.24). Find out why, and make the code correct everywhere.

D2. A map lookup that always says "not found"

Java
Map<Long, String> byId = new HashMap<>();
byId.put(5L, "dosa");
System.out.println("byId.get(5) = " + byId.get(5) + " | byId.get(5L) = " + byId.get(5L));
Terminal
byId.get(5) = null | byId.get(5L) = dosa

It compiles with -Xlint:all and no warnings. Why does get(5) miss, and why didn't the compiler stop it?

D3. The menu planner that serves everything after day 2

A scheduling method decides what's cooked each day:

Java
String plan = "";
switch (day) { case 1: plan += "idli "; case 2: plan += "dosa "; case 3: plan += "vada "; default: plan += "closed"; }

For day = 2 the kitchen gets dosa vada closed. Find the bug, then rewrite the method so that both this bug and "forgot a new day" become compile errors.

D4. ArrayStoreException in a method that compiled cleanly

A utility fills an array of "anything" with defaults:

Java
static void fillDefaults(Object[] slots) { for (int i = 0; i < slots.length; i++) if (slots[i] == null) slots[i] = 0; }
...
String[] names = new String[3];
names[0] = "idli";
fillDefaults(names);

It throws java.lang.ArrayStoreException: java.lang.Integer at run time. Explain why it compiled, why it failed, and how to make the compiler catch it.

Career-oriented

Interview prep

Each question has a How to get there note: the way of thinking that produces a strong answer. The general method from chapter 01's companion applies: restate, pick a spine, walk it, add one level of depth, close with the "so what".

Mid level

Q1. Is Java pass-by-value or pass-by-reference? Show it with code, and explain what a method can and can't do to its caller's objects.

How to get there. The interviewer is testing whether you know the third term. Spine: what's copied (always the value: for objects, the value is a reference) → what the callee can do (mutate the shared object) → what it can't (rebind the caller's variable) → the name (call by sharing). Then prove it with two tiny methods: one that calls list.add (the caller sees it) and one that does list = new ArrayList<>() (the caller doesn't).

Q2. When would you use an exception, an error return value, and a Result/Optional-style type? Give a TiffinBox example of each.

How to get there. Avoid "exceptions are bad". Build a small decision rule along two questions: is the failure expected as part of normal business? (sold out: yes; out of memory: no), and must every caller handle it? Then map: expected and must-handle → a result type the compiler forces you to inspect; unexpected or programmer error → an exception; hot paths or C-style APIs → error values. Give one example each and say where in the system the handling happens.

Senior level

Q3. A team's service passes Lists between layers and you keep seeing bugs where data changes "on its own". How do you diagnose and fix this class of bug, not just the instance?

How to get there. Spine: symptom → mechanism (aliasing: two parts of the code hold references to one mutable object) → diagnosis (find who else holds the reference) → fix the instance → fix the class (make the default safe so new code can't reintroduce it). The senior part is the last step: policies, types and tooling, not heroics.

Q4. You're designing the error model for a payment client library used by ten teams. What do you decide, and why?

How to get there. A library's error model is an API that's hard to change later, so start from the callers' decisions, not from your implementation: what will each caller do with each failure? Group failures by that (retry, show the user, alert, crash), then choose representations, then cover the non-obvious requirements: idempotency, preserving causes, not leaking secrets, versioning. Chapter Exercises S2 is the full design exercise; this question is the five-minute spoken version.

Staff level

Q5. Your organisation has 2 million lines of Java with nulls everywhere, and NullPointerExceptions are a top cause of incidents. Propose a strategy.

How to get there. Staff answers are about changing a large system and many teams safely over time. Spine: measure (where do NPEs come from?), stop the bleeding (new code), contain (boundaries), migrate (by risk), enforce (tooling), know you've won (metric). Mention specific tools and why a big-bang rewrite is wrong.

Q6. Two senior engineers argue: one wants a functional style (immutable records, pure functions, streams), the other a classic OO domain model (rich objects with behaviour and state). How do you resolve it for the order domain?

How to get there. Don't pick a winner in the abstract. Turn the argument into criteria tied to the domain: which parts change together, where invariants live, how much concurrency there is, what the team knows, how it will be tested. Often the answer is a principled mix: say where each style goes and why, and capture it in an ADR. Theoretical gap 5 (closures and objects are two sides of one idea) is a good line to defuse a religious debate.