AlgoViz

Verifying and extending a design

medium 40 min

Before 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

0:00 / 4:30

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

  1. 1949

    Alan Turing gives a paper called Checking a Large Routine, on how to be sure that a program is right.

  2. 1967

    Robert Floyd publishes Assigning Meanings to Programs: statements about the state are attached to points in the program.

  3. 1969

    Tony Hoare publishes rules to reason from what is true before a step to what is true after it.

  4. 1970

    Edsger Dijkstra writes in Notes on Structured Programming that testing can show the presence of bugs, but never their absence.

  5. 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.

Step 1 of 4

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.

Lee, Noor and the bridge
MAX 3SHOW MEWITH A TRAIN

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

IdRequirement
R1A station has a fixed number of docks. Renting gives the bike with the lowest number
R2A rider has at most one bike at a time
R3A bike can be returned at any station with a free dock. If it is full, the ride goes on
R4The first 30 minutes are free. After that, each started 15 minutes cost 100 cents
Time is counted in whole minutes. Two invariants: every bike is in exactly one place, and no station holds more bikes than docks.

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.

Python
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 quarters
The draft. Run it: a usual ride gives the right answer.
Edit and run it in your browser

Step 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

TimeCallnorthsouthridesAnswerCheck
0start1 23none3 bikes
0rent(asha, north)23asha: 113 bikes
40give_back(asha, south)23nonefull2 bikes: bike 1 is lost
The ride was removed before the check. The table shows it at once. In your head you see only the refusal, and the refusal is correct.

The lost bike

Change first, check second. The refusal is right, and the state is wrong.

How to trace aloud

  1. 1

    Set the scene

    Say the starting values and write them as a row. Two or three objects are enough.

  2. 2

    Read what is written

    Put your finger on the line. Do not say what it should do. Say what it does.

  3. 3

    Write only changes

    One new row for each public call. Between two calls nothing else may change.

  4. 4

    Check the rules

    After each row, say the invariants: three bikes, none above the docks.

  5. 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

MinutesPaid minutesDraftR4 saysVerdict
30000right
3111 // 15 + 1 = 1, so 100100right
441414 // 15 + 1 = 1, so 100100right
451515 // 15 + 1 = 2, so 200100wrong
461616 // 15 + 1 = 2, so 200200right
603030 // 15 + 1 = 3, so 300200wrong
Only multiples of 15 fail. The usual test values 10, 35 and 50 would never find it. To round up with whole numbers: add 14, then divide by 15.

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?

Two traces and one small table take about three minutes. Name the rest.

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

open ridesBikeShare- rides: Map<Rider, Ride>- fleet: List<int>+ rent(rider, station): int+ giveBack(rider, station)+ snapshot()+ check()Station- docks: int- bikes: sorted List+ take(): int+ put(bike)Ride+ bike: int+ started: int

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

You do not need a framework for this. In Python both seams are plain functions.

How do you prove in a test that a refused return changes nothing?

BreaksOnly expect the error
How
Call, and check that NoDock is 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 nameCaseWould it find a draft fault?
fare at each edge30, 31, 45, 46, 60, 61Yes: rounding
full station keeps the ride openrefusal, snapshot, then go onYes: the lost ride
one ride per riderthe same call twiceYes: the overwritten ride
nothing to take, nothing to returnempty, wrong orderYes: the draft raises IndexError and KeyError
random calls keep the rules2000 calls, check after eachYes: both lost bikes
returns the farea happy path with 50 minutesNo
A name says the behaviour, not the method. 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 * 100

Lines 7 to 8

One parent for all refusals. The random test will catch this one and nothing else. A KeyError must still fail.

1 of 3

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.

QuestionStaysNewRule or cost
E-bikes cost moreStations, rent, returnFare gets the kind of bike. Bike is a small class, not a numberEdit: Fare and Ride. One more test table
A monthly passAll of BikeShareA fare that looks up the riderFare needs the rider: ask now if more facts will follow, and pass the ride
Reserve a bike for 10 minutesReturn, fareReservations with an end timeA third place for a bike: the invariant and check change
A broken bikeRent, farereport moves it to a workshopA fourth place for a bike
Show the nearest free dockAll commandsA query over stations, with positionsNone, it only reads
Two riders at the same momentSignaturesOne lock around check and changeTrace: both see the last bike. See Correctness
Restart without lossRulesA store for rides and bikesBoth changes of a move in one transaction
Reservations are the interesting row: a new place for a bike means that the sentence each bike is in exactly one place must be edited. Say that aloud.

Extension: a monthly pass

BikeShare+ rent(rider, station)+ giveBack(rider, station)«interface»Fare+ cents(rider, minutes): intPayAsYouGo+ cents(rider, minutes)

1/4What stays

BikeShare asks for a price. It does not know how one is made.

usesimplements

PassFare holds another Fare and falls back to it.

Where does the new requirement land?

Adding a seam for one case is not needed. A plain method is a fine answer. See YAGNI and Open/closed.

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

Draw this before any code. Every new arrow is a method or a rule, and each needs one row in a trace.
Python
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))
Expiry by comparing times. No timer is needed, and the edge is a decision: at the end time itself the reservation is over.
Edit and run it in your browser

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?

ToolShowsDoes not showIn the round
TraceEvery state of one storyOther storiesTwo of them, written
Named testOne fact, for everCases without a nameFour names
Random runOrders nobody plannedThat there is no bugOne sentence, or ten lines
Reasoning from invariantsAll inputs, if each writing line is readMistakes in the sentence itselfFor the richest method
Check on live dataWhat really happenedIt is lateOne sentence at the end
The tools have different blind spots. Two different ones are better than twice as much of one.

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.

Sources