AlgoViz

Class design: state and behaviour

medium 40 min

A 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

0:00 / 4:41

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

RememberDoRule
R1places, startcreateplaces 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

KindWhat the caller gets
course is fullresultOutcome.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

    major

    One path forgets to update it, and the two facts disagree.

    Wrong
    self.booked.add(member)self.free -= 1
    Right
    def free_places(self):    return self._places - len(self._booked)
  • One bool for four reasons

    major

    The caller cannot tell full from late from twice.

    Wrong
    def book(self, member) -> bool
    Right
    def book(self, member, now) -> Outcome# raises AlreadyIn, TooLate
  • Change before the check

    critical

    A refused call leaves half of the work behind.

    Wrong
    self._booked.remove(member)if now > limit: raise TooLate()
    Right
    if now > limit: raise TooLate()self._booked.remove(member)
  • The rule sits in the caller

    critical

    The second caller does not know it.

    Wrong
    course.booked.remove(m)if course.waiting:    course.booked.add(course.waiting.popleft())
    Right
    promoted = course.cancel(m, now)
  • Reading the clock deep inside

    minor

    No test can choose 16:01.

    Wrong
    def book(self, member):    if datetime.now() >= self._starts_at: ...
    Right
    def 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