Class design: state and behaviour
medium 40 minA requirement becomes something a class must remember, something it must do, or a rule it must keep.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
From requirements to a table, and from the table to objects that keep their rules.
Operations
Six sentences, one table
Each requirement fills one row: remember, do, rule.
Step 1 of 6
R1
| Remember | Do | Rule | |
|---|---|---|---|
| R1 | places, start | create | places 1 or more |
| R2 | |||
| R3 | |||
| R4 | |||
| R5 | |||
| R6 |
Places and a start time must last. Creating a course with no place is refused.
Step 1: R1
- Good for
- The first minutes of class design
- Watch out
- Empty cells are fine
A row that remembers nothing new is good news.
In the real world
The same class design: state and behaviour doing real jobs. Pick one and step through it.
Six situations and the answer that fits each one.
Step 1 of 6
Full
| Kind | What the caller gets | |
|---|---|---|
| course is full | result | Outcome.WAITING |
| not in the line | ||
| 20 minutes left | ||
| books twice | ||
| zero places | ||
| no such id |
A requirement says what happens: a normal result.
Step 1: Full
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A stored value that can be worked out
majorOne path forgets to update it, and the two facts disagree.
Wrongself.booked.add(member)self.free -= 1Rightdef free_places(self): return self._places - len(self._booked)One bool for four reasons
majorThe caller cannot tell full from late from twice.
Wrongdef book(self, member) -> boolRightdef book(self, member, now) -> Outcome# raises AlreadyIn, TooLateChange before the check
criticalA refused call leaves half of the work behind.
Wrongself._booked.remove(member)if now > limit: raise TooLate()Rightif now > limit: raise TooLate()self._booked.remove(member)The rule sits in the caller
criticalThe second caller does not know it.
Wrongcourse.booked.remove(m)if course.waiting: course.booked.add(course.waiting.popleft())Rightpromoted = course.cancel(m, now)Reading the clock deep inside
minorNo test can choose 16:01.
Wrongdef book(self, member): if datetime.now() >= self._starts_at: ...Rightdef book(self, member, now): if now >= self._starts_at: ...
Interview tips
Draw the table
- One row per requirement
- Three columns and an owner
- Say the empty cells aloud
Say signatures
- Name, inputs, result, errors
- Read it as a sentence
- No flags
Name invariants
- Two to four sentences
- Point at lines that write
- Write them as check()
Leave things out
- No field without a row
- No setter
- No class with only a getter