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

Class design: state and behaviour

1:03Reel

Theory

Read or listen first. About 2 min.

What it is

Class design is the step between a list of entities and code. For each class you decide four things: what it remembers (state), what others may ask or tell it (behaviour), what is always true (invariants) and how it says no (errors).

The source is always the requirements. Every verb becomes a method on the class that owns the data. Every fact that must survive until the next call becomes a field. Every at most, only if and never becomes an invariant or an error.

The result is small: one box per class, with fields, method signatures and two or three sentences of rules. You can check it against the requirements before a single method body exists.

Why it exists

Bodies are cheap to change, signatures are not. Once three classes call book(member), adding a time to it changes all three. Five minutes on signatures save the last fifteen minutes of a round.

A field without a requirement is a fact that somebody must keep correct for nothing. A requirement without a method is a feature you forgot. The table shows both at a glance.

An invariant gives you a test for every method at once. You do not ask is this code right?. You ask is the rule still true on each line where the method can stop?.

A short history

  1. 1972

    David Parnas argues that a module should hide a decision that is likely to change, instead of being one step of a flow chart.

  2. 1986

    Bertrand Meyer begins to publish on design by contract: what a method may expect, what it promises, and what stays true for every object of a class.

  3. 1989

    Kent Beck and Ward Cunningham present cards with a class name, its responsibilities and its collaborators, as a way to teach object thinking.

  4. 1989

    Rebecca Wirfs-Brock and Brian Wilkerson describe a responsibility-driven approach: begin with what an object does, not with its data.

  5. 2003

    Martin Fowler names the anemic domain model: classes with data and no behaviour, while the rules sit in services around them.

Words to know

State
What an object must remember between two calls.
Behaviour
What an object answers or does when it is called.
Derived value
Something that can be worked out from the state, so it is not stored.
Signature
Method name, parameters, result and the ways it can refuse.
Invariant
A sentence about the state that is true before and after every public call.
Precondition
What must be true for a call to be accepted.
Command and query
A command changes something. A query only answers.
Domain error
A rule of the business said no, such as too late.
Programming error
The caller broke the contract, such as a course with zero places.
Anemic class
A class with fields, getters and setters, and no rules.

How it works

Step through the idea, or press Play.

Step 1 of 4

Table. Requirement, remember, do, rule, owner

Understand it

Start here

A place for each thing

A boat cabin is small and it moves. A thing without a place falls on somebody's foot. Asha and Max are fitting one out before their first trip.

Asha, Max and the cabin

Requirements first, then places, then rails, then one tap. The same order works for classes.

The example

Six sentences from a yoga studio

We design one small system all the way: members book places in courses of a studio. The requirements are agreed, and the entities are found (that work is in From prompt to requirements and Finding entities and owners).

The agreed requirements

IdRequirement
R1A course has a fixed number of places, at least one, and a start time
R2A member books a place. If the course is full, they join the end of a waiting line
R3A member is in a course at most once, booked or waiting
R4A booked member may cancel until two hours before the start. The first in line gets the place
R5Nobody books after the start. Leaving the line is always allowed
R6Everyone can see how many places are free, and their position in the line
Out of scope: payment, trainers, rooms, messages. Entities kept: Studio, Course. Rejected: Member (an id is enough), Place (nobody picks a certain mat), WaitingLine (a queue inside Course).

Step 1

The derivation table

Take one sentence at a time and fill a row. Do not think about code. A cell may stay empty.

FromMust rememberMust doMust stay trueOwner
R1places, start timecreate a courseplaces is 1 or moreCourse
R2who is booked, the line in orderbooknobody waits beside a free placeCourse
R3nothing newrefuse a second bookingbooked and waiting share nobodyCourse
R4the limit of two hourscancel, move the first one upbooked is never more than placesCourse
R5nothing newcompare with the current timeno change of booked after the startCourse
R6nothing: both can be worked outfree places, waiting positionCourse
Entry pointcourses by id, a clockfind the course and pass the call onone course per idStudio
Two rows say nothing new, and that is good news. The table also shows that Studio has little to do. It is an entry point, not the brain.

Where does a sentence go?

Four tests for a field

  • Which row?

    Name the requirement that needs it. No row, no field.

  • Does it survive?

    If only one call needs it, it is a local variable or a parameter.

  • Can I work it out?

    free is places minus booked. Store it only if measuring shows that the sum is too slow.

  • Who changes it?

    If two classes change it, it has no owner yet.

Python
class Course:    def __init__(self, places):        self.places = places        self.booked = set()        self.free = places              # the same fact, stored twice    def book(self, member):        self.booked.add(member)         # adding the same member again changes nothing        self.free -= 1                  # but this line counts them twicec = Course(3)c.book("asha")c.book("asha")print("stored:", c.free)                        # 1print("true:  ", c.places - len(c.booked))      # 2
Why a stored counter is a risk. One path forgets it, and the two facts disagree. Run it.
Edit and run it in your browser

Step 2

Who should own the rule?

The rule nobody waits beside a free place needs the places, the booked members and the line. One class holds all three, so the rule belongs there. If a rule needs data of two objects, it goes to the smallest class that holds both. See Tell, don't ask.

The bad shape: a bag of data and a service that does everything

Course+ places: int+ startsAt: Date+ free: int+ booked: List+ waiting: List+ get and set for all five

1/3Only data

Course has public lists and a stored counter. It cannot protect anything.

uses

Two arrows reach into the same data. Each must know all the rules.

The good shape: the rules stand around the data

Course- places: int- startsAt: Date- booked: Set<Id>- waiting: Queue<Id>+ book(member, now): Outcome+ cancel(member, now): Id?+ freePlaces(): int+ waitingPosition(m): int?

1/4State, private

Four fields, each with a row in the table. No free field.

owns (dies together)depends on

Now there is one door. The admin page must use it as well.

Step 3

Signatures that tell the truth

A signature is a promise in one line. Say it aloud in the round: book takes a member and the time, and answers booked or waiting. It raises AlreadyIn or TooLate.

WeakBetterWhy
process(data)book(member, now)The name is the verb of the requirement
book(...): boolbook(...): OutcomeFalse could mean full, late or twice. The caller has to guess
setWaiting(list)no such methodA setter lets a caller break every rule
getBooked(): SetfreePlaces(): intAnswer the question. Do not hand out the inside
cancel(member, force)cancel and remove_by_staffA flag is two methods in one name
book(member) that reads the clockbook(member, now)A test can choose the time
book(member, places)book(member, now)The object already knows its places

How does book say that the course is full?

BreaksReturn false
How
True means booked, False means anything else.
Limit
Full, late and twice look the same, and the waiting line has no answer at all.
Choose when
Never, if there is more than one reason.
WorksRaise CourseFull, then call join_waiting
How
The caller catches the error and calls a second method.
Limit
Between the two calls a place may become free. Then a person waits beside a free place. Every caller must also know the two-step rule.
Choose when
When joining the line is a choice of the member and not automatic.
StrongOne call with Outcome.BOOKED or WAITING
How
Full is an expected case in R2, so it is a result. Only broken rules are errors.
Limit
Adding a third outcome means that callers must handle it. With an enum the compiler or a linter can find them.
Choose when
When the requirement describes what happens in that case.

Result, empty or error?

In our class: full is a result, no position in the line is empty, too late is a domain error, zero places is a programming error.

Step 4

Invariants in plain words

InvariantFromWhich line could break it?
booked is at most placesR1booked.add without a look at free places
If somebody waits, no place is freeR2, R4booked.remove without moving the first one up
Nobody is booked and waitingR3moving up without removing from the line
Nobody waits twiceR3waiting.append without a check
For each invariant, look only at the lines that write its fields. There are few, because the fields are private.

An invariant may be broken inside a method for a moment. Between booked.remove and booked.add one place is free while somebody waits. That is allowed as long as nobody can look. This is why one method does both, and why the two lines need one lock when threads meet. See Correctness: races on shared state.

One member in one course

Drawing the life of one thing shows missing methods. Every arrow needs a line of code.

Step 5

Check first, change last

Every method that changes something has the same three parts: refuse, change, answer. If a check comes after a change, a refused call leaves half of the work behind.

Refuse, change, answer

  • All checks stand at the top
  • A refused call changes nothing
  • The answer is worked out at the end
  • One look shows every reason to refuse

Change, then find out

  • The old booking is gone, the new one fails
  • Every error path needs an undo
  • The undo can fail too
  • Tests pass, because they use good inputs

A cancel that moves somebody up

Course answers who moved up. Telling Noor about it is somebody else's job.

Code

The design becomes code

Read each part with the table beside it. Every line should point to a row.

Studio and Course

Names for everything the caller can meet. They come first because signatures use them.

from __future__ import annotationsfrom collections import dequefrom datetime import datetime, timedeltafrom enum import Enumfrom typing import Callableclass Outcome(Enum):    BOOKED = "booked"    WAITING = "waiting"class CourseError(Exception):    """A rule of the studio said no. Nothing has changed."""class AlreadyIn(CourseError): passclass NotIn(CourseError): passclass TooLate(CourseError): passclass UnknownCourse(CourseError): pass

Lines 8 to 10

Two normal answers of book. With a bool, the caller could not tell waiting from refused.

1 of 3

Why it is built this way

  • I keep programming errors separate: zero places is a ValueError, not a CourseError.

Before you write bodies: five checks in one minute

  1. 1

    Cover

    Point at each requirement and at its method. One without a method is a gap.

  2. 2

    Justify

    Point at each field and at its row. One without a row goes out.

  3. 3

    Say it

    Read one signature as a sentence. If you need and, split it.

  4. 4

    Break it

    For each invariant, try to write a call that breaks it. If you can, close that door.

  5. 5

    Change it

    Invent one new requirement. Count the classes that change.

Second example

The same table on a savings jar

A child's savings jar in an app: put money in, take money out, set a goal, see the progress. Four sentences give one small class.

RequirementRememberDoRuleDecision
Put money inbalance in centsput(cents)cents above 0Whole cents, no floating point
Take money outnothing newtake(cents)balance never below 0NotEnough carries what is missing
Set a goalgoal in centsset_goal(cents)goal above 0A setter with a rule is a real method
See progressnothingprogress(): int0 to 100Worked out. 100 is the most, even above the goal
See the last ten movesa list of movesrecent(n)balance is the sum of movesNow balance could be worked out too
The last row changes the class: if every move is kept, the balance can be worked out. Keep both only with the rule in the last cell as a tested invariant.

Limits

Not every class needs rules

Summary

The whole topic in one minute.

Read each requirement as remember, do, or rule. Put it on the class that owns the data. Drop every field that can be worked out from another one.

Write signatures before bodies: the name says the intent, the result says every normal outcome, errors say what is refused. Check first, change last, so a refused call changes nothing.

Write two to four invariants in plain words. They protect the class, and later they are your tests.

  • Each requirement says remember, do, or rule. Put it into a table with an owner.
  • No row, no field. What can be worked out is a method.
  • The result covers every normal outcome. Errors are for refused calls, one name for each reason.
  • Invariants are sentences. Private fields make the lines that can break them few.
  • Check first, change last, answer at the end.
  • Hand in the clock and other outside things, so that a test can choose them.

Sources