Verifying and extending a design
medium 40 minBefore you say done, run your own code with real values and write down what each field holds.
Video lesson · Chapter 1 of 6
Make a prediction
Verifying and extending a design
1:03Reel
Theory
Read or listen first. About 2 min.
What it is
Verification in a design round means that you show that the code does what was agreed. You pick concrete inputs, walk through the code line by line, and write down the state after each call. Then you name the tests that would keep it right.
Extension is the question that comes next: what if we also need ...?. The answer is a short walk over your own classes. You say which signature stays, which class is new, which invariant changes, and what it costs.
Both use the same skill: reading your own code as it is written, and not as you meant it.
Why it exists
Most bugs in a round are small: a limit on the wrong side, a change before a check, a second call by the same person. You see them in the first trace, or the interviewer sees them first.
Finding your own bug is a strong signal. It shows how you work when nobody watches. Saying it should work shows the opposite.
An extension question tests the design without asking about it. If one sentence of new requirements touches five classes, a responsibility is in the wrong place.
A short history
1949
Alan Turing gives a paper called Checking a Large Routine, on how to be sure that a program is right.
1967
Robert Floyd publishes Assigning Meanings to Programs: statements about the state are attached to points in the program.
1969
Tony Hoare publishes rules to reason from what is true before a step to what is true after it.
1970
Edsger Dijkstra writes in Notes on Structured Programming that testing can show the presence of bugs, but never their absence.
1989
Kent Beck writes SUnit, a small test framework for Smalltalk. It was later adapted for Java as JUnit.
Words to know
- Trace
- A table of the state after each call, made by hand from the code.
- Happy path
- The usual case in which nothing is refused.
- Boundary
- The values on both sides of a limit, such as 30 and 31 minutes.
- Invariant check
- A method that tests what must always be true.
- Fake
- A small working stand-in, such as a clock that a test can set.
- Property test
- A test that tries many generated inputs against a general rule.
- Model
- A simpler, slower version that gives the right answer to compare with.
- Seam
- A place where behaviour can be replaced without an edit of the code around it.
- Regression test
- A test that fails with an old bug, so that the bug cannot return unseen.
How it works
Step through the idea, or press Play.
Trace. Real values, state after each call
Understand it
Start here
Show me with a train
Lee has built a toy bridge and is proud of it. Noor has a box of wagons. A bridge is not finished because it stands. It is finished when it has carried what the sign says.
Frames 1 to 3 are cases, 4 is a trace, 5 is a missing case, 6 is regression, 7 is an extension.
The example
A small bike share
The agreed requirements
| Id | Requirement |
|---|---|
| R1 | A station has a fixed number of docks. Renting gives the bike with the lowest number |
| R2 | A rider has at most one bike at a time |
| R3 | A bike can be returned at any station with a free dock. If it is full, the ride goes on |
| R4 | The first 30 minutes are free. After that, each started 15 minutes cost 100 cents |
Here is a first draft. It looks reasonable and the happy path works. Before you read on, find what is wrong. There are three faults.
class Draft: def __init__(self): self.docks = {"north": 2, "south": 1} self.bikes = {"north": [1, 2], "south": [3]} self.rides = {} # rider -> (bike, started) def rent(self, rider, station, now): bike = self.bikes[station].pop(0) self.rides[rider] = (bike, now) return bike def give_back(self, rider, station, now): bike, started = self.rides.pop(rider) if len(self.bikes[station]) == self.docks[station]: raise RuntimeError("full") self.bikes[station].append(bike) paid = max(0, now - started - 30) return (paid // 15 + 1) * 100 if paid else 0d = Draft()print(d.rent("asha", "north", 0)) # 1print(d.give_back("asha", "north", 50)) # 200: 20 minutes are two started quartersStep 1
Trace with real values
Choose a small world: two stations, three bikes, and one station that is full. Small numbers make the odd case happen at once. Then fill one row for each call.
The draft, traced
| Time | Call | north | south | rides | Answer | Check |
|---|---|---|---|---|---|---|
| 0 | start | 1 2 | 3 | none | 3 bikes | |
| 0 | rent(asha, north) | 2 | 3 | asha: 1 | 1 | 3 bikes |
| 40 | give_back(asha, south) | 2 | 3 | none | full | 2 bikes: bike 1 is lost |
The lost bike
How to trace aloud
- 1
Set the scene
Say the starting values and write them as a row. Two or three objects are enough.
- 2
Read what is written
Put your finger on the line. Do not say what it should do. Say what it does.
- 3
Write only changes
One new row for each public call. Between two calls nothing else may change.
- 4
Check the rules
After each row, say the invariants: three bikes, none above the docks.
- 5
Stop at the first surprise
Say: here the ride is gone, and the bike is in no station. I move the check up. Fix, then start that trace again.
Step 2
Choose the cases that break things
Six questions that find cases
Zero, one, full
An empty station, the last bike, the last dock.
Both sides of a limit
30 and 31 minutes, 45 and 46.
Twice
The same rider rents again. The same ride is returned again.
Wrong order
Return before rent.
Refused
After a no, is everything as before?
Other door
Is there a second way to reach the same state?
The fare at each edge
| Minutes | Paid minutes | Draft | R4 says | Verdict |
|---|---|---|---|---|
| 30 | 0 | 0 | 0 | right |
| 31 | 1 | 1 // 15 + 1 = 1, so 100 | 100 | right |
| 44 | 14 | 14 // 15 + 1 = 1, so 100 | 100 | right |
| 45 | 15 | 15 // 15 + 1 = 2, so 200 | 100 | wrong |
| 46 | 16 | 16 // 15 + 1 = 2, so 200 | 200 | right |
| 60 | 30 | 30 // 15 + 1 = 3, so 300 | 200 | wrong |
The third fault is a question about twice: Asha rents bike 1, and then bike 2. The second line overwrites the first ride. Bike 1 is lost again, this time without any error.
How deep should you go?
Step 3
Where a design lets you test
The random and slow parts come in from outside: the clock and the fare. Then a test can choose the minute and the price. The technique itself is in Dependency inversion and Unit testing OO code.
The design and its seams
1/4The core
BikeShare owns stations and open rides. A bike is in a station or in a ride, never in both.
owns (dies together)usesimplements
How do you prove in a test that a refused return changes nothing?
BreaksOnly expect the error
- How
- Call, and check that
NoDockis raised. - Limit
- The draft raises an error as well, and still loses the bike.
- Choose when
- Never alone, when the call changes state.
WorksCheck the field that you thought of
- How
- After the error, ask if the ride is still open.
- Limit
- You check only what you expected to break. Another field may have changed.
- Choose when
- Very small classes.
StrongCompare a whole snapshot, and go on
- How
- Snapshot before and after must be equal. Then return the bike elsewhere and check the fare.
- Limit
- The snapshot needs a method or equality on the classes. It must copy, or it changes with the object.
- Choose when
- Every method that can refuse.
Step 4
Name the tests
| Test name | Case | Would it find a draft fault? |
|---|---|---|
| fare at each edge | 30, 31, 45, 46, 60, 61 | Yes: rounding |
| full station keeps the ride open | refusal, snapshot, then go on | Yes: the lost ride |
| one ride per rider | the same call twice | Yes: the overwritten ride |
| nothing to take, nothing to return | empty, wrong order | Yes: the draft raises IndexError and KeyError |
| random calls keep the rules | 2000 calls, check after each | Yes: both lost bikes |
| returns the fare | a happy path with 50 minutes | No |
test_give_back_2 tells you nothing when it fails.A test that helps
- One behaviour, readable in ten seconds
- Own small world, no shared state
- Uses public methods
- Fails with the bug, passes without it
A test that hurts
- Checks private fields
- Needs the real clock or a sleep
- Copies the formula of the code
- Passes when a line is deleted
Code
The fixed program and its tests
BikeShare
The fare is a pure function, so it can be tested with a table.
from __future__ import annotationsimport randomfrom dataclasses import dataclassfrom typing import Callableclass ShareError(Exception): """A rule said no. Nothing has changed."""class NoBike(ShareError): passclass NoDock(ShareError): passclass AlreadyRiding(ShareError): passclass NotRiding(ShareError): passdef fare_cents(minutes: int) -> int: paid = max(0, minutes - 30) return (paid + 14) // 15 * 100Lines 7 to 8
One parent for all refusals. The random test will catch this one and nothing else. A KeyError must still fail.
Step 5
Extension questions
The interviewer now changes the world. Answer in four parts, always in this order: what stays, what is new, which rule changes, what it costs.
| Question | Stays | New | Rule or cost |
|---|---|---|---|
| E-bikes cost more | Stations, rent, return | Fare gets the kind of bike. Bike is a small class, not a number | Edit: Fare and Ride. One more test table |
| A monthly pass | All of BikeShare | A fare that looks up the rider | Fare needs the rider: ask now if more facts will follow, and pass the ride |
| Reserve a bike for 10 minutes | Return, fare | Reservations with an end time | A third place for a bike: the invariant and check change |
| A broken bike | Rent, fare | report moves it to a workshop | A fourth place for a bike |
| Show the nearest free dock | All commands | A query over stations, with positions | None, it only reads |
| Two riders at the same moment | Signatures | One lock around check and change | Trace: both see the last bike. See Correctness |
| Restart without loss | Rules | A store for rides and bikes | Both changes of a move in one transaction |
Extension: a monthly pass
1/4What stays
BikeShare asks for a price. It does not know how one is made.
usesimplements
Where does the new requirement land?
Worked extension
Reserve a bike for ten minutes
This one hurts, so it is worth doing once. Stays: the fare, returning, the docks. New: a reservation with rider, bike and end time. Rule: a bike is docked, reserved or riding. Cost: rent has a second path, and check counts a third place.
Where a bike can be
class Shelf: # only the part that is new HOLD = 10 def __init__(self, bikes): self.docked = sorted(bikes) self.held = {} # rider -> (bike, end) def _release_expired(self, now): for rider, (bike, end) in list(self.held.items()): if now >= end: del self.held[rider] self.docked = sorted(self.docked + [bike]) def reserve(self, rider, now): self._release_expired(now) if rider in self.held: raise ValueError("has a reservation") if not self.docked: raise ValueError("no bike") self.held[rider] = (self.docked.pop(0), now + self.HOLD) def take(self, rider, now): self._release_expired(now) if rider in self.held: return self.held.pop(rider)[0] if not self.docked: raise ValueError("no bike") return self.docked.pop(0)s = Shelf([1])s.reserve("asha", 0)try: s.take("lee", 9)except ValueError as e: print("minute 9:", e)print("minute 10: lee gets", s.take("lee", 10))A decision for the interviewer: the reserved bike still stands in its dock. So the number of used docks is docked plus reserved. If you forget that, a returned bike finds a free dock on paper and none on the street.
Judgement
How sure must you be?
| Tool | Shows | Does not show | In the round |
|---|---|---|---|
| Trace | Every state of one story | Other stories | Two of them, written |
| Named test | One fact, for ever | Cases without a name | Four names |
| Random run | Orders nobody planned | That there is no bug | One sentence, or ten lines |
| Reasoning from invariants | All inputs, if each writing line is read | Mistakes in the sentence itself | For the richest method |
| Check on live data | What really happened | It is late | One sentence at the end |
Summary
The whole topic in one minute.
Trace three things: one usual case, one refusal, and one boundary. Write the state after each call, and compare it with the invariants.
Name tests as sentences about behaviour. Hand in the clock and other outside things, so that tests need no waiting and no network.
Answer an extension in four parts: what stays, what is new, which rule changes, and what it costs. If much must change, say so and say why.
- Run your code by hand with real values, and write the state after each call.
- Usual case, refusal, both sides of a limit, the same call twice.
- A refused call must leave the same snapshot.
- Expected values come from the requirement, never from the code.
- Random calls with a seed and a check after each step find orders you did not think of.
- Extension: what stays, what is new, which rule changes, what it costs.