AlgoViz

From prompt to requirements

medium 35 min

The prompt is one sentence.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:49

From prompt to requirements

1:02Reel

Theory

Read or listen first. About 3 min.

What it is

A requirement is a sentence about the system that can be true or false. "The room should be easy to use" cannot be checked. "A resident may hold at most two machines" can: you can write the test before you write the class.

A functional requirement says what the system does: start a machine, return a ticket, refuse a third one. A non-functional requirement says how well it does it: safe with several callers, fast enough, easy to extend, possible to test. In an object design round both end up in code. The first become methods. The second become locks, interfaces and data structures.

The spec is the short list you agree on. It has four parts: what it must do, how well, what you assume, and what is out of scope. The last part is not a weakness. It is the part that lets you finish.

Why it exists

The prompt is short on purpose. The interviewer wants to see whether you build what was asked or what you remembered. Two candidates with the same prompt may need different classes, because they got different answers.

A question is cheap now and expensive later. When you learn after thirty minutes that several people press buttons at the same time, every method you wrote has to be opened again.

A written spec is also your checklist. At the end you point at each line and say which method fulfils it. Without a list, "done" is only a feeling. Verifying a design starts from this list.

A short history

  1. 1984

    The IEEE publishes standard 830, a guide to writing software requirements specifications. It is replaced in 2011 by ISO/IEC/IEEE 29148, whose current revision is from 2018.

  2. 1987

    Ivar Jacobson presents use cases in an article at the OOPSLA conference: describe a system by what its actors do with it.

  3. 1994

    Dai Clegg describes the MoSCoW order: must have, should have, could have, won't have this time.

  4. 1997

    RFC 2119 (March) defines what the words MUST, SHOULD and MAY mean in internet standards. In the same year Kent Beck introduces user stories in the C3 project at Chrysler.

  5. 2001

    The team at Connextra in London shares the story form with a role, a goal and a reason. Ron Jeffries describes the three Cs: card, conversation, confirmation.

  6. 2006

    Dan North publishes Introducing BDD, with acceptance criteria in the form given, when, then.

Words to know

Prompt
What the interviewer says first. Usually one sentence.
Spec
The agreed list: functions, qualities, assumptions, out of scope.
Actor
Whoever or whatever starts something: a person, another program, a timer.
Functional requirement
Something the system does. It becomes a method and a test.
Non-functional requirement
How well it does it. It becomes a lock, a data structure, an interface or a limit.
Invariant
A sentence that is true before and after every call, such as one machine runs at most one cycle.
Acceptance check
A small example with a start, an action and an expected result.
Scope
The border between what you build in this round and what you only name.
Assumption
A default you chose because nobody answered. Say it aloud, so that it can be corrected.
YAGNI
You aren't gonna need it. The reason why a feature without a sentence gets no class.

How it works

Step through the idea, or press Play.

Step 1 of 5

Say it back. Repeat the prompt in your own words

Understand it

The tailor who measures before cutting
WaistcoatHatOne jacket, please!

The tape costs five minutes. The cloth costs the whole round.

Idea

Only ask what changes the cut

You could ask fifty questions about a laundry room. The good ones have one property: two possible answers lead to two different designs. Before you ask, finish this sentence in your head: "If they say yes I will add ..., if they say no I will ...". If both halves are equal, do not ask.

Same theme, two questions

Weak questionWhy it is weakQuestion that changes the design
What colour is the screen?No class depends on itDo several panels press at the same time? (lock or no lock)
How many users in total?A number without a decisionMust everything fit in one process? (objects or services)
Should it be fast?Always yesWhich call is the frequent one? (the structure to choose)
Which database?Not an object questionMust the state survive a restart? (a storage interface or none)
Can I use Singleton?That is your jobIs there one room or several? (one object or many)

Step 1

Say the prompt back and name the actors

Our running example: "Design the laundry room of a student house." Say it back with the main path in it: "So residents come down, start a washing machine or a dryer, pay, come back later and take their clothes out. Is that the core?" This is ten seconds. It catches the case where they meant something else, such as a company that collects laundry.

Then name who acts. An actor is whoever starts something: a resident, a caretaker, a timer, the card reader. Actors are outside the system. Most of them will never be classes. They tell you which methods must exist.

Actors outside, one door inside

Left: who calls you. Right: whom you call. Things on the right become interfaces, because you do not own them.

Step 2

The seven measures

Seven themes, and their first letters spell MEASURE. Go through them in this order. You will skip one or two that the prompt already answers.

  • Members

    Who or what starts something? People, programs, timers. Who may do what?

  • Events

    What are the two to four main actions, in order? What comes back from each?

  • Amounts

    How many, how long, how much money? Limits per person. Whole cents and minutes?

  • Sorry cases

    Full, late, twice, wrong person, not paid. What is a normal answer and what is an error?

  • Users at once

    Can two calls meet? What must never happen twice? Can something fail in the middle?

  • Rules that change

    Which rule will have a second version: price, choice, limit? Which is fixed?

  • Edges

    In memory or stored? Screen or only classes? One site or many? What is not built today?

Each measure, and what an answer turns into

MeasureAsk in the laundry roomIf the answer is AIf the answer is B
MembersDoes a person start machines, or a card reader?start(resident, kind)start(card, kind) and a lookup
EventsDoes a finished machine become free by itself?Only a time is storedA call empty, and a state between
AmountsIs there a limit per resident?Count cycles per personNo counting at all
Sorry casesWhat if all machines run?Return nothingA waiting line with rules of its own
Users at onceOne panel or several?Plain codeCheck and take in one locked step
Rules that changeWill prices depend on the hour?A number on the kindA pricing interface
EdgesMust it survive a restart?Objects in memoryA store behind an interface
Read the two right columns. They differ in every row. That is the test for a good question.

Is this question worth asking?

Five minutes, word for word

  1. Interviewer

    Design the laundry room of a student house.

  2. You

    Residents start a washer or a dryer, pay, and take their clothes out later. Is that the core, or do you also want people to book a time ahead?

  3. Interviewer

    The core. No booking.

  4. You

    I assume a handful of machines in one room, and a fixed programme per kind: a wash takes 40 minutes and a dryer 60. All right?

  5. Interviewer

    Fine.

  6. You

    When the programme ends, the clothes are still inside. Is the machine free then, or only when its owner has emptied it?

  7. Interviewer

    Good point. Only when it is emptied.

  8. You

    And if everything is taken: do people wait in a line that we manage, or is the answer simply no?

  9. Interviewer

    Simply no. But tell them how long it will take.

  10. You

    Then I need a query for the shortest remaining time. Can several panels be used at the same moment?

  11. Interviewer

    Yes, there are two doors with a panel each.

  12. You

    So two people may reach for the last washer together, and one of them must get a clean no. Last one: is there a limit per person, and will prices change often?

  13. Interviewer

    Two machines per person. Prices are fixed.

Step 3

Write sentences that can be false

Write while you talk, where the interviewer can see it. Use numbers, so that you can point at "R4" later. One sentence, one fact. Start with who or what, then must or must not.

The spec of the laundry room

No.SentenceBecomesCheck
R1A resident can start a free machine of a kindstart(resident, kind)Start a washer: a cycle comes back
R2Starting charges the price of the kindPayments.charge300 cents for a washer
R3A machine stays taken until its owner empties itempty(resident, machine)At 41 minutes it is still taken
R4Only its owner can empty a machine, and only when it has finishedA check in emptyWrong person: refused
R5A resident can hold at most 2 machinesA count, limitThird start: refused, nothing charged
R6If all are taken, the answer is nothing, and no money movesstart returns nothingFifth washer: nothing
R7Anyone can ask when the next machine finishesminutes_left(kind)0 when one is free
Q1Two panels never start the same machineOne lock around check and takeMany threads, one machine, one winner
Q2It can be tested at any minute of the dayThe clock is passed inSet the time, no waiting
Q3More machines need no codeThe machines are a mapBuild a room with 1 machine
R is what it does, Q is how well. Ten lines are enough for a 45 minute round.

Can be checked

  • At most 2 machines per resident
  • Returns nothing when all are taken
  • Prices are whole cents
  • Two panels never start the same machine

Cannot be checked

  • The system should be user friendly
  • Handles load well
  • Payment must be secure
  • Flexible for the future

Step 4

Qualities: the five that change object code

Long lists of qualities sound good and do little. In an object design round five of them change what you type. For each, make it concrete, and name the line of code that it buys.

From a quality to a line of code

QualityConcrete versionWhat it buysWhen to drop it
Correct with several callersThe last machine has one winnerA lock, or one atomic takeOne caller for sure
ExtensibleA new price rule is one new classAn interface on that rule onlyThe rule is fixed: use a number
TestableAny minute, no networkClock and card service passed inNever, it costs one parameter
Fast enoughFinding a free one takes O(1)A queue of free ones per kindSix machines: a loop is fine
Safe to retry or failA failed charge leaves no half startOrder of steps, or undoNothing outside can fail

The classic pair for a parking lot is "atomic: no double booking" and "scales to 10,000 spots". Make both concrete. No double booking: find and take happen in one step. Ten thousand spots: that is a small number for one process, so it does not need servers, but a linear search at every gate is worth replacing. Consistency inside one process is a matter of locks. Network failure only counts when there is a network.

Step 5

Out of scope, with a reason and a place

Say three or four things that a reasonable person could expect and that you will not build. Give each one a reason, and say where it would fit. The place is what turns a refusal into a design statement.

The second card, on the nail

Not nowWhyWhere it would fit
Booking aheadYou said no bookingA calendar per machine, asked before start
Waiting lineFull is a plain noBetween start and the free machines
Topping up a cardAnother system owns the moneyBehind Payments
Broken machinesNobody asked, smallA flag that takes a machine out of the map of free ones
Messages when doneUseful, but a second topicA listener on the end of a cycle, see Observer

The interviewer says: "You decide what is in scope." What do you do?

BreaksTake everything
How
Booking, waiting line, payments, messages, reports. It sounds complete.
Limit
You will have twelve classes without methods at minute 40.
Choose when
Never.
WorksTake only the happy path
How
Start and empty, nothing else.
Limit
Nothing is left to discuss. Limits, refusals and two panels are where the design shows.
Choose when
The round is 20 minutes, or the code must run.
StrongOne full path, its refusals, one hard part
How
"I take start and empty with all their refusals, and two panels at once as the hard part. Booking and messages are on the list, and I will show where they fit."
Limit
You must say it in one breath and get a nod.
Choose when
Nearly always.

In, later, or out

Step 6

Read it back and look for collisions

Reading back takes twenty seconds: "Start, empty, at most two, full means nothing, two panels, fixed prices. No booking and no line. Did I miss anything you want to see?" Listen to the answer. A small hint here ("the two panels are interesting") often tells you where the second half of the round will go.

While you read, look for two sentences that cannot both be true. Typical pairs: "every request gets a machine" and "a resident holds at most two". "The machine is free after 40 minutes" and "only the owner empties it". "First come, first served" and "staff go first". Say the collision and offer a rule: "The limit wins, and the refusal says why."

The agreement, as a conversation

Design

What the spec does to the class diagram

The two drawings below answer the same prompt. The first was drawn before any question. The second was drawn from the ten sentences.

Drawn before the questions

LaundryRoom+ book(slot)+ start(machine)+ notify(resident)MachineFactory+ create(type)

1/4A room, and a pattern

The first two boxes come from habit. A factory is there because the word machine has kinds. Nobody has said that kinds behave differently.

usesowns (dies together)

Every box is defensible. Together they answer a question that nobody asked.

Drawn from the ten sentences

LaundryRoom- busy: Map<int, Cycle>- limit: int+ start(resident, kind)+ empty(resident, machine)+ minutes_left(kind)

1/5Verbs become methods

R1, R3 and R7 are the three things people do. They become the three public methods of one class.

owns (dies together)uses

How the boxes are found is the topic of Finding entities and owners.

Code

From the sentences to code that runs

The spec has done its work when the code can be read next to it. Watch the numbers R1 to R7 and Q1 to Q3 in the explanations.

The laundry room, sentence by sentence

The nouns that carry facts, and one named refusal for each sorry case.

from dataclasses import dataclassfrom enum import Enumfrom threading import Lockclass Kind(Enum):    WASHER = (40, 300)    DRYER = (60, 200)    def __init__(self, minutes: int, cents: int):        self.minutes = minutes        self.cents = centsclass LimitReached(Exception): passclass NotYours(Exception): passclass StillRunning(Exception): pass@dataclass(frozen=True)class Cycle:    machine: int    kind: Kind    resident: str    ends_at: int

Lines 6 to 12

The assumption from minute one: a fixed programme and a fixed price per kind. As data it can be changed in one line. As two subclasses it would be the same two numbers in two files.

1 of 3

Why it is built this way

  • Full is not in the list of exceptions. R6 says it is a normal answer, and normal answers are return values.

Change one answer

What if they had said: people wait in a line?

One answer was "simply no". Suppose it had been "put them in a line". It sounds like one more method. Look at how many new questions it brings: How long is a turn held? Can you leave the line? Does your place count against the limit? May somebody who walks in take a free machine while others wait?

The same room with a waiting line

The new rules live in a class of their own. The room only asks whose turn it is.

from collections import dequeclass WaitingLine:    def __init__(self, clock, hold=5):        self._clock, self._hold = clock, hold        self._people = deque()        self._called_at = None    def join(self, who: str) -> int:        if who not in self._people:            self._people.append(who)        return self._people.index(who) + 1    def leave(self, who: str) -> None:        if who in self._people:            if self._people[0] == who:                self._called_at = None            self._people.remove(who)    def turn(self) -> str | None:        """Whose turn it is. Call it only when something is free."""        while self._people:            if self._called_at is None:                self._called_at = self._clock()            if self._clock() - self._called_at < self._hold:                return self._people[0]            self._people.popleft()            self._called_at = None        return None

Lines 5 to 8

The hold is the answer to: how long do we wait for the person whose turn it is? Without it, one person who went home blocks the room for ever.

1 of 4

Case study

A smart parking lot: from prompt to spec

The same method on the best known prompt of all: "Design a smart parking lot." Here only the spec is made. The whole design is in Parking lot, and the step from this spec to classes is in Finding entities and owners.

First list, then sentences that can be false

First noteMeasureBetter sentence
Multi-floor parkingAmountsThe lot has several floors. The layout is read when it is built
Different vehicle types (car, bike)AmountsA car needs a car space. A bike may use any space
User can scan a ticketEventsleave takes the number of a ticket
User can pay by card or cashRules that changePayment is an interface with two implementations
System assigns a spotEventsenter chooses a fitting free space and returns a ticket
Hourly billingRules that changeEach started hour costs the rate of the type
Ticket generationEventsEach entry creates one ticket, which can be used once
Concurrency (multiple gates)Users at onceTwo gates never give out the same space
10k spots capacityAmountsFinding a space does not walk through all 10,000
High consistencyUsers at onceNumber of taken spaces equals number of open tickets, always
Add payment methodsRules that changeA third method is one new class
The first two columns are how people take notes. The third column is what you can build and check.

Three scope questions and what hangs on them

"City-wide and distributed" is a fair answer, but then it is no longer an object design round. Say: "I will design one building, with an interface that a city service could call." Nearly always the interviewer agrees.

Practice

Three more prompts, three hidden questions

The question that splits the design

PromptQuestionAnswer AAnswer B
Tic-tac-toeAlways 3 x 3, or n x n with k in a row?Eight fixed linesCount in four directions from the last move
Vending machineCan money be put in before a choice?One price checkStates, and a way to cancel
Expense sharingEqual parts only, or percent and exact sums?One division, and where the rest cent goesA split interface
Meeting roomsCan a meeting repeat every week?A sorted list of slotsRules that produce slots, with exceptions
Logging libraryMay a slow destination hold up the caller?Write directlyA queue and a worker

When you get no answer at all

  1. 1

    Choose

    Take the simplest version that still has one hard part.

  2. 2

    Say

    "I will assume two panels and at most two machines per person."

  3. 3

    Write

    Put an A in front of the sentence, so that it is visible as an assumption.

  4. 4

    Hide it

    Keep it in one place in the code, so that the other answer is one change.

Summary

The whole topic in one minute.

Seven measures turn a prompt into a spec: Members, Events, Amounts, Sorry cases, Users at once, Rules that change, Edges. Ask the one or two questions per measure whose answers would change a class, a structure or a lock.

Write eight to ten sentences that can be true or false, read them back, and write down what you leave out. Then every sentence becomes a method, a field or a test, and the round has a finish line.

  • Ask only questions whose two answers lead to two designs. Ask with a default.
  • MEASURE: Members, Events, Amounts, Sorry cases, Users at once, Rules that change, Edges.
  • Eight to ten numbered sentences that can be true or false.
  • Qualities count when you can name the line of code that they buy.
  • Out of scope needs a reason and a place.
  • Read back, look for two sentences that collide, get a yes, stop.

Sources