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
See it run
Run the code by hand: every call, every field, every rule.
Operations
Trace a usual ride
Asha takes bike 1 and returns it after 45 minutes.
Step 1 of 6
Write the start
North has bikes 1 and 2. South has bike 3 and is full. Three bikes in all.
Step 1: Write the start
def rent(self, rider, station_id): if rider in self._rides: raise AlreadyRiding(rider) bike = self._stations[station_id].take() self._rides[rider] = Ride(bike, self._clock()) return bikedef give_back(self, rider, station_id): ride = self._rides.get(rider) if ride is None: raise NotRiding(rider) self._stations[station_id].put(ride.bike) del self._rides[rider] return self._fare(self._clock() - ride.started)- Good for
- The first trace
- Watch out
- It proves little alone
Say what the line does, not what it should do.
In the real world
The same verifying and extending a design doing real jobs. Pick one and step through it.
Six calls that nobody planned. After each one, the rules are checked.
Step 1 of 6
Call 1
| Call | Answer | State | |
|---|---|---|---|
| 1 | rent lee south | bike 3 | ok |
| 2 | |||
| 3 | |||
| 4 | |||
| 5 | |||
| 6 |
Lee takes the only bike in south.
Step 1: Call 1
Common mistakes
The bugs interviewers watch for, with the fix beside each.
It should work
majorThat sentence is about what you meant. The trace is about what you wrote.
Wrong# done, I thinkRight# north 1 2, south 3, rides none# rent(asha, north) -> north 2, rides asha: 1Only the error is tested
criticalThe draft raises an error too, and loses a bike.
Wrongrefused(NoDock, lambda: city.give_back("asha", "south"))Rightbefore = city.snapshot()refused(NoDock, lambda: city.give_back("asha", "south"))assert city.snapshot() == beforeThe test repeats the formula
majorBoth are wrong in the same way, and the test passes.
Wrongassert fare_cents(45) == (15 // 15 + 1) * 100Rightassert fare_cents(45) == 100Random without a seed
majorIt fails at night and never again.
Wrongrng = random.Random()Rightrng = random.Random(7)Every extension is free
minorNobody believes it. Name the edit and its cost.
Wrong"My design supports that already."Right"Fare and one call change. Stations stay."
Interview tips
Trace
- Two or three objects
- One row for each call
- Say the rules after each row
Break it
- Empty and full
- Both sides of a limit
- The same call twice
Name tests
- A sentence about behaviour
- Values from the requirement
- Snapshot after a refusal
Extend
- What stays, what is new
- Which rule is edited
- What it costs