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
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
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.
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.
1989
Kent Beck and Ward Cunningham present cards with a class name, its responsibilities and its collaborators, as a way to teach object thinking.
1989
Rebecca Wirfs-Brock and Brian Wilkerson describe a responsibility-driven approach: begin with what an object does, not with its data.
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.
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.
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
| Id | Requirement |
|---|---|
| R1 | A course has a fixed number of places, at least one, and a start time |
| R2 | A member books a place. If the course is full, they join the end of a waiting line |
| R3 | A member is in a course at most once, booked or waiting |
| R4 | A booked member may cancel until two hours before the start. The first in line gets the place |
| R5 | Nobody books after the start. Leaving the line is always allowed |
| R6 | Everyone can see how many places are free, and their position in the line |
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.
| From | Must remember | Must do | Must stay true | Owner |
|---|---|---|---|---|
| R1 | places, start time | create a course | places is 1 or more | Course |
| R2 | who is booked, the line in order | book | nobody waits beside a free place | Course |
| R3 | nothing new | refuse a second booking | booked and waiting share nobody | Course |
| R4 | the limit of two hours | cancel, move the first one up | booked is never more than places | Course |
| R5 | nothing new | compare with the current time | no change of booked after the start | Course |
| R6 | nothing: both can be worked out | free places, waiting position | Course | |
| Entry point | courses by id, a clock | find the course and pass the call on | one course per id | Studio |
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?
freeis 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.
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)) # 2Step 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
1/3Only data
Course has public lists and a stored counter. It cannot protect anything.
uses
The good shape: the rules stand around the data
1/4State, private
Four fields, each with a row in the table. No free field.
owns (dies together)depends on
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.
| Weak | Better | Why |
|---|---|---|
process(data) | book(member, now) | The name is the verb of the requirement |
book(...): bool | book(...): Outcome | False could mean full, late or twice. The caller has to guess |
setWaiting(list) | no such method | A setter lets a caller break every rule |
getBooked(): Set | freePlaces(): int | Answer the question. Do not hand out the inside |
cancel(member, force) | cancel and remove_by_staff | A flag is two methods in one name |
book(member) that reads the clock | book(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
Truemeans booked,Falsemeans 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?
Step 4
Invariants in plain words
| Invariant | From | Which line could break it? |
|---|---|---|
| booked is at most places | R1 | booked.add without a look at free places |
| If somebody waits, no place is free | R2, R4 | booked.remove without moving the first one up |
| Nobody is booked and waiting | R3 | moving up without removing from the line |
| Nobody waits twice | R3 | waiting.append without a check |
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
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
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): passLines 8 to 10
Two normal answers of book. With a bool, the caller could not tell waiting from refused.
Why it is built this way
- I keep programming errors separate: zero places is a
ValueError, not aCourseError.
Before you write bodies: five checks in one minute
- 1
Cover
Point at each requirement and at its method. One without a method is a gap.
- 2
Justify
Point at each field and at its row. One without a row goes out.
- 3
Say it
Read one signature as a sentence. If you need
and, split it. - 4
Break it
For each invariant, try to write a call that breaks it. If you can, close that door.
- 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.
| Requirement | Remember | Do | Rule | Decision |
|---|---|---|---|---|
| Put money in | balance in cents | put(cents) | cents above 0 | Whole cents, no floating point |
| Take money out | nothing new | take(cents) | balance never below 0 | NotEnough carries what is missing |
| Set a goal | goal in cents | set_goal(cents) | goal above 0 | A setter with a rule is a real method |
| See progress | nothing | progress(): int | 0 to 100 | Worked out. 100 is the most, even above the goal |
| See the last ten moves | a list of moves | recent(n) | balance is the sum of moves | Now balance could be worked out too |
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
- Beck and Cunningham: A laboratory for teaching object-oriented thinking (OOPSLA 1989)
- Parnas: On the criteria to be used in decomposing systems into modules (1972)
- Meyer: Applying design by contract
- Martin Fowler: Anemic domain model
- Java: BlockingQueue
- PostgreSQL: constraints
- Stripe: PaymentIntent lifecycle
- Kubernetes: objects, spec and status