Incremental TDD Pair Session: Building a Java Set

Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

You are participating in a navigator-driver Test-Driven Development (TDD) pairing round where you speak through every decision while the interviewer writes the Java and JUnit code at the keyboard. Together, you incrementally construct a custom Set class from an empty file—one unit test and one minimal production edit at a time.

Throughout the coding portion, asymptotic time and memory efficiency are intentionally out of scope. Instead, the interviewer evaluates whether every line of production code is strictly forced by a failing unit test and represents the bare minimum needed to turn the suite green (for example, isEmpty() requires zero element storage until later tests demand remembering inserted items). Because your partner types, clear verbal direction, behavioral test naming, and calm joint debugging matter just as much as the code itself.

Clarify any open contract details up front (such as core operations like isEmpty(), add(x), contains(x), remove(x), and size(), return values, starting element type, null behavior, .equals() vs. ==, and whether basic list delegation is permitted), then walk through three stages:

  1. Test design and ordering: Sequence the operations and individual JUnit cases—covering positive behaviors, negative checks, edge cases, and cross-operation interactions—so each new test fails for a single, predictable reason.
  2. Minimal Red-Green-Refactor execution: Direct the step-by-step code changes from an empty class, explaining why each change is minimal, when earlier shortcuts become obsolete, how to refactor safely while green, and how to diagnose unexpected test failures together.
  3. Future evolution (verbal discussion): Without writing additional code, explain how you would extend the API, introduce generic element types with clear equality/hashing contracts, and upgrade internal storage for large-scale performance while relying on your existing test suite.

Scope & Expectations

  • Clarify open API rules first and order small, descriptive JUnit tests from least state required to most state required, including duplicates, absent removals, and value equality.
  • Apply strict Red-Green-Refactor discipline at every step—starting from constants and single fields before introducing a collection, and removing redundant state while green.
  • Communicate crisp, unambiguous instructions to the driver and demonstrate hypothesis-driven collaborative debugging when a test fails.
  • Articulate how to scale the class later with richer set operations, generics, equals/hashCode invariants, and O(1) hash-based storage without rewriting behavioral tests.

Step-by-step walkthrough

  1. Clarify the API and agree on the TDD loop

    Because you are navigating verbally while the interviewer types, spend the first two minutes pinning down the open rules. Every answer you agree on becomes a concrete unit test later:

    • Minimal set API: Start with isEmpty(), add(x), contains(x), remove(x), and size(). Keep void add and void remove at first; returning a boolean flag when membership changes can be added later if time permits.
    • Element type: Start with String rather than generics (SimpleSet<T>) so the first tests need minimal boilerplate.
    • null policy: Disallow null elements — add(null) throws NullPointerException, while contains(null) returns false.
    • Equality rule: Two elements count as the same when a.equals(b) is true (value equality), not only when a == b (reference identity, meaning the exact same object in memory).
    • Backing storage: Delegating to java.util.ArrayList is allowed once multiple elements must be stored, since runtime complexity is explicitly out of scope during coding.

    State the Red-Green-Refactor loop (the three-phase cycle of Test-Driven Development, or TDD) out loud so your partner knows what to expect at every turn:

    1. RED       Dictate ONE small JUnit test, predict how it will fail, and run it.
    2. GREEN     Dictate the smallest, simplest code change that turns all tests green.
    3. REFACTOR  While all tests are green, remove duplicated state or outgrown shortcuts, then re-run.
    

    Dictate clearly enough that your partner never has to guess variable or method names — for example: "In SimpleSetTest, add @Test void setContainsAddedElement(). Create SimpleSet set = new SimpleSet(), call set.add("apple"), and call assertTrue(set.contains("apple"))."

  2. Part 1: Order operations and unit tests so each forces one change

    Order the operations from least state required to most state required (isEmpty -> add -> contains -> size -> remove -> contracts), and sequence the unit tests (small, isolated automated checks of one behavior) so each new test fails for one exact reason:

    Test #  Descriptive JUnit method name                   Smallest state / logic forced
    ------  ----------------------------------------------  -------------------------------------------
      1     newSetIsEmpty                                   SimpleSet class; isEmpty() returns true
      2     setIsNotEmptyAfterAdd                           add(x) + single `boolean empty = true`
      3     newSetContainsNothing                           contains(x) returns false
      4     setContainsAddedElement                         contains(x) returns !empty
      5     setDoesNotContainElementThatWasNeverAdded       remember 1 item: `String singleElement`
      6     setContainsEveryAddedElement                    remember N items: `List<String> elements`
            -> [Refactor while green: derive isEmpty() from elements.isEmpty(); delete `boolean empty`]
      7     newSetHasSizeZero                               size() returns 0
      8     sizeCountsDistinctAddedElements                 size() returns elements.size()
      9     addingDuplicateDoesNotIncreaseSize              if (!elements.contains(x)) before adding
     10     removedElementIsNoLongerContained               remove(x) calls elements.remove(x)
     11     setIsEmptyAfterRemovingOnlyElement              catches stale-boolean bug if not refactored
     12     removingOneElementKeepsOtherElements            interaction: remove + contains on survivors
     13     removingAbsentElementLeavesSetUnchanged         negative case on remove
     14     duplicateAddedElementIsGoneAfterSingleRemove    interaction: duplicate add + single remove
     15     containsComparesByEqualsNotReferenceIdentity    value equality contract (distinct objects)
     16     addingNullThrowsNullPointerException            null policy + set stays unchanged
    

    Notice how every operation gets positive cases, negative cases (empty set, absent item), and interaction cases (how add duplicates affect size and remove, and how remove affects isEmpty).

  3. Part 2a: Grow `isEmpty` and `add` from a constant to one boolean

    Test 1 (newSetIsEmpty): - Red: Does not compile yet because SimpleSet and isEmpty() do not exist.

    @Test
    void newSetIsEmpty() {
        SimpleSet set = new SimpleSet();
        assertTrue(set.isEmpty());
    }
    
    • Green: Hard-code return true;. Nothing in the test suite has added an element yet, so any field or list would be speculative code.
    public class SimpleSet {
        public boolean isEmpty() {
            return true;
        }
    }
    

    Test 2 (setIsNotEmptyAfterAdd): Call set.add("apple"), then assertFalse(set.isEmpty()). - Red: Fails because isEmpty() still returns true. - Green: Add private boolean empty = true; and set empty = false; inside add. Do not store "apple" yet — no test asks what was added! Tell the interviewer out loud: "I know empty cannot become true again once remove exists; a later interaction test will force us to replace it."

    public class SimpleSet {
        private boolean empty = true;
    
        public boolean isEmpty() {
            return empty;
        }
    
        public void add(String element) {
            empty = false;
        }
    }
    
  4. Part 2b: Grow `contains` from zero, to one field, to a list

    Here we follow the classic TDD "0 -> 1 -> many" progression:

    1. Test 3 (newSetContainsNothing): assertFalse(new SimpleSet().contains("apple")).
      • Green: Add public boolean contains(String candidate) { return false; }.
    2. Test 4 (setContainsAddedElement): set.add("apple"); assertTrue(set.contains("apple"));.
      • Green: Change contains to return !empty;. Because no test queries a different string yet, reusing the boolean is genuinely the simplest passing change.
    3. Test 5 (setDoesNotContainElementThatWasNeverAdded): set.add("apple"); assertFalse(set.contains("pear"));.
      • Red: !empty wrongly returns true for "pear".
      • Green: Store one String singleElement field. Check this.singleElement != null before calling .equals(candidate) so calling contains on an empty set (or with null) never throws NullPointerException:
    public class SimpleSet {
        private boolean empty = true;
        private String singleElement;
    
        public boolean isEmpty() {
            return empty;
        }
    
        public void add(String element) {
            empty = false;
            this.singleElement = element;
        }
    
        public boolean contains(String candidate) {
            return this.singleElement != null && this.singleElement.equals(candidate);
        }
    }
    
    1. Test 6 (setContainsEveryAddedElement): Add "apple" and "pear", then assert both contains("apple") and contains("pear") are true.
      • Red: singleElement overwrites "apple" with "pear", so contains("apple") fails.
      • Refactor-first option (while green): If the interviewer asks you to refactor while tests are green before adding behavior, mark Test 6 @Disabled temporarily. Replace singleElement with List<String> elements = new ArrayList<>() where add runs elements.clear(); elements.add(element); — Tests 1–5 stay green because behavior is unchanged. Then re-enable Test 6 and delete elements.clear(); (a tiny one-line change) to turn Test 6 green!
      • Refactor out duplicated state immediately: Once Test 6 passes, both boolean empty and elements track emptiness. Having two sources of truth invites bugs. While all 6 tests are green, change isEmpty() to return elements.isEmpty();, delete private boolean empty, and re-run all 6 tests.
  5. Part 2c: Add `size`, reject duplicates, and implement `remove`

    Now each remaining core operation takes tiny, clean steps:

    • Test 7 (newSetHasSizeZero): assertEquals(0, new SimpleSet().size()) -> Green: return 0;.
    • Test 8 (sizeCountsDistinctAddedElements): Add "apple" and "pear", expect 2 -> Green: return elements.size();.
    • Test 9 (addingDuplicateDoesNotIncreaseSize): Call set.add("apple") twice, expect size() == 1.
      • Red: ArrayList.add appends blindly, failing with expected: <1> but was: <2>.
      • Green: Guard add with if (!elements.contains(element)).
    • Test 10 (removedElementIsNoLongerContained): Add "apple", call set.remove("apple"), assert !set.contains("apple") -> Green: elements.remove(element);.
    • Tests 11–14 (setIsEmptyAfterRemovingOnlyElement, removingOneElementKeepsOtherElements, removingAbsentElementLeavesSetUnchanged, duplicateAddedElementIsGoneAfterSingleRemove):
      • Because we refactored isEmpty() to delegate to elements.isEmpty() and prevented duplicate entries in add(), Tests 11–14 pass right away.
      • Verify each immediately-green test can fail: Whenever a new test passes on the first run, ask the interviewer to temporarily comment out elements.remove(element) (or if (!elements.contains(element))), watch the test turn red for the expected reason, and restore the line. That proves the test is not vacuously green.
  6. Part 2d: Test value equality, null rejection, and collaborative debugging

    Test 15 (containsComparesByEqualsNotReferenceIdentity): In Java, string interning causes two identical string literals "apple" and "apple" in source code to point to the exact same String object in memory, so a buggy == check would accidentally pass! Construct two distinct objects and prove they are distinct with assertNotSame:

    @Test
    void containsComparesByEqualsNotReferenceIdentity() {
        String stored = new String("apple");
        String probe = new String("apple");
        assertNotSame(stored, probe);
    
        SimpleSet set = new SimpleSet();
        set.add(stored);
        assertTrue(set.contains(probe));
    }
    

    How to debug together if Test 15 fails: Suppose earlier at Test 6 you had written a manual loop for (String item : elements) { if (item == candidate) return true; }. Tests 1–14 would all pass (thanks to string interning), and Test 15 would fail with expected: <true> but was: <false>. Walk through your debugging thought process out loud: 1. Read the assertion failure (contains(probe) returned false). 2. State a hypothesis: "Our loop compares object references with == instead of value equality with .equals()." 3. Verify assertNotSame(stored, probe) succeeded above, confirming two separate String instances were used. 4. Apply the minimal fix (item.equals(candidate), or delegate to elements.contains(candidate) which uses equals), then run the full suite.

    Test 16 (addingNullThrowsNullPointerException): Assert assertThrows(NullPointerException.class, () -> set.add(null)) and assertTrue(set.isEmpty()) -> Green: add Objects.requireNonNull(element, "element must not be null"); at the top of add. Here is the finished SimpleSet:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Objects;
    
    public class SimpleSet {
        private final List<String> elements = new ArrayList<>();
    
        public boolean isEmpty() {
            return elements.isEmpty();
        }
    
        public void add(String element) {
            Objects.requireNonNull(element, "element must not be null");
            if (!elements.contains(element)) {
                elements.add(element);
            }
        }
    
        public boolean contains(String element) {
            return elements.contains(element);
        }
    
        public void remove(String element) {
            elements.remove(element);
        }
    
        public int size() {
            return elements.size();
        }
    }
    
  7. Part 3: Expand the set with richer operations, O(1) hashing, and generics

    When coding stops, clarify whether "expand" means more operations, scaling to large input sizes, or type generality, and address all three concisely:

    • Additional operations (and the tests driving each):
      • Boolean return values on add/remove: addReturnsTrueWhenNewElementAdded, addReturnsFalseWhenDuplicateAdded, removeReturnsFalseWhenElementAbsent.
      • Iteration (Iterable<T>): iteratorVisitsEveryElementExactlyOnce — collect yielded items into a List, check list.size() == set.size(), and compare sorted copies (never assert a fixed iteration order, since sets are unordered).
      • Set algebra: union, intersection, and difference tested on disjoint sets, overlapping sets ({a, b} and {b, c} -> union size 3, intersection {b}), empty sets, and set.union(set).
    • Scaling storage from O(n) to O(1) average time:
      • Right now elements.contains(x) scans the list linearly (O(n)). Inserting n = 100,000 distinct elements performs 0 + 1 + 2 + ... + 99,999 = n(n - 1) / 2 ≈ 5 × 10^9 (5 billion) equals comparisons!
      • Replacing ArrayList with a hash table (an array of buckets indexed by element.hashCode(), giving O(1) average add/contains/remove, or a balanced binary search tree for O(log n) sorted order) drops 100,000 inserts to roughly 100,000 bucket lookups.
      • Because Tests 1–16 only call public methods (isEmpty, add, contains, remove, size), every existing test stays 100% unchanged as a regression safety net! Add new storage-stress tests: inserting 10,000 elements across table resizes, and inserting distinct objects with a constant hashCode() (return 42;) to verify hash collision handling.
    • Generics and element contracts (SimpleSet<T>):
      • Parameterize SimpleSet<T> (noting a classic Java overload trap: on List<Integer>, list.remove(5) removes index 5, whereas list.remove((Object) element) removes the value).
      • Document two required contracts on T: (1) if a.equals(b) is true, then a.hashCode() == b.hashCode() must hold, and (2) elements must not be mutated in a way that changes equals/hashCode while stored in the set.

Intuition & how it works

Think of Test-Driven Development (TDD) (a workflow where you write a failing automated test before writing any production code) like climbing a rock face using safety pitons: before you reach up for the next handhold, you clip in one small safety pin (RED: write one small unit test, an isolated automated check of a single behavior, and watch it fail), make the smallest movement that reaches that pin (GREEN: write the simplest possible code that passes), and tidy your footing while clipped in safely (REFACTOR: clean up duplication without changing behavior while all tests pass). In a pair-programming format where the interviewer types your instructions, this tiny step size proves two skills at once: disciplined incremental design and crystal-clear verbal communication.

The naive instinct in interviews is to immediately dictate a full HashSet with a bucket array, resizing math, generics, and a size counter before running a single test. That approach fails this exercise's core evaluation criteria because you write dozens of untested lines at once, introduce multiple bugs simultaneously when a test finally runs, and violate the core rule of writing only the minimal logic demanded by the active failing test.

Walk through how the first 6 tests grow SimpleSet from zero state to a list one forced change at a time:

  1. newSetIsEmpty fails because the class does not exist -> return the constant true from isEmpty() (0 fields).
  2. setIsNotEmptyAfterAdd calls add("apple") and expects isEmpty() == false -> add a single boolean empty = true flipped to false inside add (still 0 elements stored).
  3. newSetContainsNothing and setContainsAddedElement ask whether "apple" is present -> contains returns false, then !empty.
  4. setDoesNotContainElementThatWasNeverAdded adds "apple" and checks contains("pear") == false -> !empty fails, forcing a single String singleElement field.
  5. setContainsEveryAddedElement adds both "apple" and "pear" -> singleElement overwrites "apple", forcing a List<String> elements = new ArrayList<>(), immediately followed by a green refactor replacing return empty; with return elements.isEmpty(); and deleting boolean empty.

Key points

  • Sequence tests from least state to most state: Start with isEmpty(), then add, contains, size, remove, and finally value-equality and null contracts so every red test fails for exactly one predictable reason.
  • Take deliberate shortcuts and name their future breaking test: Using boolean empty or String singleElement on purpose — while stating out loud which upcoming test will break it — shows the interviewer your small steps are intentional discipline, not oversight.
  • Eliminate duplicated state during Refactor: As soon as List<String> elements is introduced, delete boolean empty and compute isEmpty() from elements.isEmpty() while tests are green so the two can never drift out of sync.
  • Cover positive, negative, and interaction cases: Test not just happy paths, but absent elements (contains("pear")), duplicate add("apple") calls (size() == 1), and cross-method interactions (add then remove -> isEmpty() is true again; two adds then one remove -> element is gone).
  • Test public behavior, never internal storage: Tests written strictly against public methods (isEmpty, add, contains, remove, size) survive swapping ArrayList (O(n) lookup) for a hash table (an array of buckets indexed by hashCode() for O(1) average lookup) with zero test edits.
  • Verify immediately-passing tests can fail: When an interaction test passes on the first try, briefly break the production line it guards, watch the test turn red, and undo the break so you know the test actually checks what its name claims.

Common mistakes

  • Building a full data structure upfront: Jumping straight to ArrayList or HashMap on Test 1 violates minimal test-driven incrementalism before any test requires element storage.
  • Writing a batch of 5 tests before writing code: Having multiple red tests at once hides which change fixed what and turns small steps into guesswork.
  • Skipping negative tests: Without setDoesNotContainElementThatWasNeverAdded, contains(x) { return !empty; } passes every positive contains test forever.
  • Testing equals with Java string literals: Because string interning (Java's reuse of a single String instance in memory for identical source literals like "apple") makes "apple" == "apple" true, a test using literals passes even when production code wrongly uses ==; always use new String("apple") plus assertNotSame.
  • Keeping both boolean empty and List<String> elements: Leaving redundant state behind causes isEmpty() to stay false forever after the last element is removed.
  • Asserting iteration order or toString() format: Sets are unordered; asserting list insertion order makes tests brittle and causes false failures when switching to a hash table.

Follow-up questions

  • After introducing remove(x), why does a standalone boolean flag for isEmpty() break down, which specific unit test exposes the defect, and what habit ensures you never miss that test? add flips empty = false, and remove cannot safely flip empty = true without knowing whether other elements still remain in the set. The test that exposes this bug is setIsEmptyAfterRemovingOnlyElement (add("apple"), remove("apple"), then assertTrue(set.isEmpty()), paired with removingOneElementKeepsOtherElements where isEmpty() must stay false). You guarantee this test gets written by following a systematic checklist: whenever you introduce a mutating method (add or remove), write an interaction test checking its effect on every existing query method (isEmpty, contains, size), and delete redundant state (boolean empty) during refactoring as soon as elements exists.
  • Suppose you replace the internal list with bucketed hash storage to reach O(1) lookups. How many of your prior unit tests should require edits, and why? Zero existing tests should require edits, because every unit test only exercises the public set contract (isEmpty, add, contains, remove, size) rather than inspecting the internal ArrayList or assuming insertion order. Any test that broke during the switch was either over-specified (for instance, asserting a specific iteration order) or used a custom test class that overrode equals without overriding hashCode (violating Java's rule that equal objects must produce identical hash codes so they land in the same hash bucket).
  • What JUnit test proves your collection checks value equality (.equals()) instead of object reference identity (==) in Java? Create two separate objects in memory with equal values — such as String stored = new String("apple") and String probe = new String("apple") (or two instances of a custom value record) — and first call assertNotSame(stored, probe) to prove stored != probe. Then call set.add(stored) and assertTrue(set.contains(probe)) (plus set.remove(probe) followed by assertTrue(set.isEmpty())), which fails immediately if the implementation uses == instead of .equals().
  • What happens to contains(x) if a caller mutates an already-inserted object so its equality and hash code change, and what contract should the class specify? Just like java.util.Set, a set's behavior when a stored element mutates its equals/hashCode state should be documented as undefined / forbidden by contract, and callers should use immutable element types (String, Integer, Java records). In our ArrayList-backed implementation, contains scans linearly on every call, so contains(newValue) returns true and contains(oldValue) returns false — though mutating one element to equal an already-stored element silently creates a duplicate in the list and breaks size() and remove(). In a hash-table-backed set, the mutated object remains stuck in the bucket computed from its old hashCode(), so contains(newValue) looks in the wrong bucket (false) and contains(oldValue) finds the bucket but fails equals() (false), making the element an unreachable "ghost" entry.

Follow-up questions

Similar questions

More Ode interview questions

All 2 Ode questions →