Finding entities and owners
medium 35 minA spec is full of nouns, and most of them are not classes.
Video lesson · Chapter 1 of 6
Make a prediction
Finding entities and owners
1:01Reel
Theory
Read or listen first. About 3 min.
What it is
An entity is a thing that your program follows over time. It has an identity: a dog that gets a new name is still the same dog. A value has no identity: two slots from 9:00 to 9:30 on the same day are simply equal, and you may swap one for the other.
An owner is the one object that may change a fact and that protects the rules about it. Everybody else asks the owner. If two objects can change the same fact, it has two owners, and sooner or later they disagree.
A relationship says how objects know each other: one owns the other, one has the other for a while, or one only uses the other for a call. Sometimes the relationship has facts of its own (since when, how long, in which role). Then the relationship becomes a class.
Why it exists
Too few classes give one large manager that knows everything. Too many give a crowd of boxes with one number each. Both are hard to change, and both cost you the round: the first has no design to discuss, the second has no time left for methods.
The choice of owners decides where bugs can live. If only one class can write the list of walks, a double walk can only be a bug in this class. If six classes can write it, you read six classes.
Interviewers listen to what you reject. "A leash is only a thing that hangs on the wall here, so I will not make it a class" shows more judgement than ten boxes.
A short history
1976
Peter Chen publishes the entity-relationship model: a world of things, and named relationships between them.
1983
Russell Abbott shows in Communications of the ACM (November) how a program design can be taken from an informal English description. Looking at the nouns and verbs of a text is still a common first step.
1989
Kent Beck and Ward Cunningham present CRC cards: class, responsibilities, collaborators, one paper card each. At the same conference Rebecca Wirfs-Brock and Brian Wilkerson present responsibility-driven design.
2003
Eric Evans publishes Domain-Driven Design, with entities, value objects and aggregates. In November Martin Fowler describes the anemic domain model: classes with data and no behaviour.
Words to know
- Entity
- A thing with an identity that is followed over time. Equal means: the same id.
- Value object
- A thing that is only its values. Equal means: the same values. Best unchanging.
- Owner
- The one object that may change a fact and guards its rules.
- Invariant
- A rule that holds before and after each call. It needs one owner.
- Composition
- The whole owns the part. When the whole goes, the part goes.
- Aggregation
- The whole has the part, but the part lives on without it.
- Association class
- A relationship with facts of its own: a walk, a loan, a booking.
- Aggregate
- A cluster of objects that is changed through one of them, its root.
- Manager class
- A class whose name says nothing about its job. Often a sign that owners are missing.
- Container, Item, Manager
- Three roles to look for in nearly every object problem: what holds, what is held, who decides.
- Anemic model
- Classes with fields only, while all rules live in services.
How it works
Step through the idea, or press Play.
Underline. Nouns and verbs of the spec
Understand it
Five underlined words, two parts. A good cast list is short.
Example
The spec we work with
The prompt: "Design the walking rota of a dog shelter." The requirements step is done (From prompt to requirements shows how). These are the sentences. Nouns are bold.
| No. | Sentence |
|---|---|
| R1 | A volunteer can book a walk with a dog for a time slot on a day |
| R2 | Two walks of one dog must not overlap, and neither must two walks of one volunteer |
| R3 | A dog is walked at most twice a day |
| R4 | Each dog needs a level of experience (easy, strong, nervous), and the volunteer must have at least this level |
| R5 | A walk can be cancelled |
| R6 | Anyone can see the walks of a dog on a day, in order |
| Q1 | Several volunteers book by phone at the same time |
| Out | Leashes, feeding, the office, reminders |
Step 1
Audition every noun
Ask three questions about each noun. One yes is enough to stay.
Identity
Do we have to tell two of them apart, and follow one of them over time?
Rule
Is there a rule that only this thing can protect, because it can see all that the rule needs?
Together
Do two or more facts always travel together, and mean something only together?
None of these
Then it is a field, an enum value, a caller, a part of the surroundings, or out of scope.
From a noun to a verdict
The audition of the dog shelter
| Noun | Verdict | Why | Becomes a class when |
|---|---|---|---|
| Dog | Entity | We follow one dog. Its level can change | It is one |
| Volunteer | Entity | R2 and R4 need to know which one, and their level | It is one |
| Walk | Relationship with facts | It joins a dog and a volunteer, and has a slot and an id to cancel | It is one |
| Time slot | Value object | Day, start and end mean something only together, and it can tell whether it overlaps | It is one, small and frozen |
| Rota | Owner | Not in bold anywhere, but R2 and R3 are about all walks together | It is one |
| Level | Enum | Three fixed words with an order | A level gets behaviour, such as a training plan |
| Day | Field | One fact, part of the slot | It owns something, such as a closing time |
| Twice a day | Constant | A number in a rule | The number depends on the dog: then a field |
| Phone | Caller | It calls book | It owns state, such as a call to be returned |
| Office, leash, feeding | Out of scope | No sentence needs them | A sentence arrives |
| Small dog, nervous dog | Not classes | They differ in one value: the level | They behave differently |
Step 2
Three roles to look for
Nearly every object problem is about things that are handed out, so three roles come back again and again. Container: what holds the things? Item: what is held? Manager: who decides? Use them as a search light, to find candidates you missed. They are not class names, and a class may play two roles.
Container, item, manager
| Problem | Container | Item | Manager | What the audition changes |
|---|---|---|---|---|
| Parking lot | Floor, spot | Vehicle, ticket | ParkingSystem | Floor is a number until it owns something. A spot holds a vehicle, and is itself held by a pool |
| Chess | Board, square | Piece | GameController | A square is a row and a column: a value. Call the manager Game |
| Library | Shelf, section | Book, member | Librarian | A book is two things: a title and a copy. The librarian is a caller. The loan is missing |
| Dog shelter | Rota | Walk | Rota | Container and manager are the same object here |
| Elevator | Building, shaft, floor | Car, request, button | Dispatcher | A floor is a number, and a button is a caller |
Use the roles
- To find a role with no name yet
- To ask who decides
- To notice that one object plays two roles
Do not
- Make three classes because there are three roles
- Call a class Manager and stop thinking
- Skip the relationships between the items
Step 3
Entity or value?
Ask: if two of them have the same contents, are they the same one? Two dogs called Bello, both strong, are two dogs. Two slots on 3 May from 9:00 to 9:30 are one and the same time. The first is an entity and needs an id. The second is a value, and should never change after it is made.
| Entity | Value object | |
|---|---|---|
| Equal when | Same id | Same contents |
| Changes | Yes, through its owner | No. Make a new one |
| Shared | By reference or id, with care | Freely |
| In Python | Class with an id | @dataclass(frozen=True) |
| In Java | Class, equals on the id | record |
| In TypeScript | Class, compare ids | readonly fields and an equals method |
| Examples | Dog, ticket, game, machine | Slot, money, position, address |
Step 4
A verb that becomes a class
"A volunteer walks a dog." The verb has facts of its own: a slot, an id, perhaps later a note about how it went. These facts belong neither to the dog nor to the volunteer. One dog has many walks, one volunteer too. So the relationship gets a class: Walk. The same happens with loan, booking, ticket, enrolment, membership and order line.
Where does the slot go?
Where do you keep who walks which dog when?
BreaksA list on both sides
- How
dog.walksandvolunteer.walks, each walk in both.- Limit
- Two truths. A cancel that forgets one side leaves a ghost: the dog is free and the volunteer is busy.
- Choose when
- Never for changing facts.
WorksA list on the dog
- How
dog.walksholds them, and the dog checks its own overlaps.- Limit
- The rule about volunteers needs all dogs, so somebody loops over all of them from outside.
- Choose when
- Only the dog has rules.
StrongAll walks in one rota
- How
WalkRotaholds the walks and checks both rules in one locked step.- Limit
- The rota can grow large. Then split it by day, because the rules never cross a day.
- Choose when
- Rules concern both sides, as here.
Step 5
One owner for each fact and each rule
Write two short lists: facts that change, and rules. For each, name the one class that may touch it. The rule of thumb: the owner of a rule is the smallest object that can see everything the rule needs.
| Fact or rule | Needs to see | Owner |
|---|---|---|
| A slot ends after it starts | Start and end | Slot, in its constructor |
| Two slots overlap | Two slots | Slot.overlaps |
| The level of a dog | The dog | Dog |
| Is this volunteer good enough? | Both levels | Volunteer.can_handle(dog) |
| No overlap for dog or volunteer | All walks of the day | WalkRota |
| At most two walks a day | All walks of the dog on the day | WalkRota |
| Which ids are used | All walks | WalkRota |
A fact with two owners drifts apart
Step 6
Relationships: owns, has, uses
Ask two questions about each pair. If A goes, does B go too? Yes means composition (filled diamond). Does A keep B for longer than one call? Yes means aggregation or a plain reference. No means it only uses B. The full story is in Aggregation vs composition, and the arrows are in UML class diagrams.
| Pair | Question | Relationship | In code |
|---|---|---|---|
| Rota and walk | Rota closed: are walks of any use? No | Owns | The rota creates and removes them |
| Rota and dog | Rota closed: the dog still lives | Has | Dogs are passed in |
| Walk and dog | The walk needs to know which | Uses | Holds a reference or an id |
| Walk and slot | The slot is part of the walk's facts | Owns a value | A frozen field |
| Dog and volunteer | Do they know each other? No | None | Only a walk joins them |
| Dog and level | One of three words | Uses | An enum |
Reference or id? Inside one process a reference is simple and fast. Use an id when the thing lives in another system, when you must not keep it alive, or when the record will be written to a store. Never both.
How many of each
Design
The same shelter, badly cast and well cast
Everybody gets a part, and one does all the work
1/4Nouns become boxes
Every noun got a box, also the leash that no rule mentions. Dog and volunteer are bags of fields that anybody may write.
usesextends (is a)
Few names, each with something to do
1/5Two entities
We follow a dog and a volunteer over time. Both have an id, and both have a level of type Level.
owns (dies together)has (lives on)uses
Code
Entities, values and the owner
The walking rota
The smallest class first. It needs nothing else, and two rules already live in it.
from dataclasses import dataclassfrom enum import IntEnumfrom itertools import countfrom threading import Lock@dataclass(frozen=True)class Slot: day: int start: int # minutes after midnight end: int def __post_init__(self): if self.end <= self.start: raise ValueError("a slot must end after it starts") def overlaps(self, other: "Slot") -> bool: return (self.day == other.day and self.start < other.end and other.start < self.end)Lines 7 to 11
Frozen, so a slot can be shared without fear. If it could change, somebody could move a walk after the rota has checked it.
Case study
A parking lot skeleton: find the two owners
Here is how the same step often looks for a parking lot. Container: ParkingLot and ParkingFloor. Item: Vehicle and ParkingSpot. Manager: EntranceGate and ExitGate. Then comes a skeleton with a pricing interface, a spot that can be booked, and a system that hands out tickets. Read it and look for a fact with two owners.
interface PricingStrategy { double calculate(long durationMinutes); }class ParkingSpot { int id; boolean isOccupied; // truth number one VehicleType type; public synchronized boolean book() { if (isOccupied) return false; isOccupied = true; return true; }}class ParkingSystem { private static ParkingSystem instance; private ConcurrentHashMap<String, ParkingSpot> activeTickets; // truth number two public Ticket generateTicket(Vehicle v) { ParkingSpot spot = findAvailableSpot(v.getType()); if (spot == null || !spot.book()) throw new RuntimeException("Full"); return new Ticket(v, spot); }}| What is wrong | What the driver sees | Better owner |
|---|---|---|
| Find and book are two steps | Two gates find the same spot. The slower one hears Full in a lot with 400 free spots | A pool that finds and takes in one step |
isOccupied and activeTickets both say who is parked | After a lost ticket they disagree | Free spots in the pool, open tickets in the lot |
| The new ticket is never put into the map | Nobody can drive out | The lot writes it in the same method |
Full is an exception, and money is a double | A normal evening looks like a crash. Cents go missing | Return nothing, and count in cents |
Also audition the cast. ParkingFloor is a number until it owns a lock or a sign. A gate is a caller until it owns a barrier. Vehicle with subclasses differs in one value. And one lot per program is a matter of creating one, not of a static field: see Singleton. Choosing the patterns for this case (Factory, Strategy, Singleton) belongs to Which pattern, when.
One owner for free, one owner for parked
A spot in the pool is free. A spot outside is not. No flag is needed.
from collections import deque@dataclass(frozen=True)class Spot: id: str kind: strclass SpotPool: def __init__(self, spots): self._free: dict[str, deque[Spot]] = {} for spot in spots: self._free.setdefault(spot.kind, deque()).append(spot) self._lock = Lock() def claim(self, kind: str) -> Spot | None: with self._lock: line = self._free.get(kind) return line.popleft() if line else None def release(self, spot: Spot) -> None: with self._lock: self._free[spot.kind].append(spot)Lines 4 to 7
The spot has lost its flag and its lock. It is a value now: where it is and what fits.
Method
Two roads, same boxes
| Road | How | Good at | Weak at |
|---|---|---|---|
| Nouns and verbs | Underline the spec | A start in one minute | Misses owners that nobody names, keeps too much |
| Responsibilities | For each rule ask who should do it, one card per class with its helpers | Finds owners, keeps classes alive | Slow without a spec |
| Life of a thing | Follow one dog, one walk from start to end | Finds states and links | Misses rules about many things |
| Tables first | Draw what would be stored | Counts (one to many) | Leads to classes without behaviour |
Saying it in the room
You
Nouns: volunteer, dog, walk, slot, level, phone, leash. Phone calls us, leash is in no sentence, so both are out. Level is three words: an enum. Slot is a value.
Interviewer
Why is a nervous dog not a subclass?
You
It differs in one value, and the value can change. If nervous dogs had a process of their own, such as two people per walk, I would first try a number on the dog, and only then a type.
Interviewer
And who checks for overlaps? The dog?
You
The dog sees only its own walks. The rule is about volunteers too. So there is an owner of all walks that the text did not name. I call it WalkRota.
Interviewer
Why not WalkManager?
You
Rota says what it holds, so reminders and printing clearly do not belong in it.
Four minutes by the clock
- 1
Underline
One minute. Nouns and verbs, aloud.
- 2
Reject
One minute. One reason each, in half a sentence.
- 3
Owners
One minute. For each rule: who can see all of it?
- 4
Connect
One minute. Owns, has or uses, and how many.
Summary
The whole topic in one minute.
Underline the nouns and audition each one: does it have an identity that is followed, a rule to guard, or facts that travel together? If not, it is a value, a field, an enum, a caller or nothing.
Then give every fact and every rule one owner. The owner of a rule is the object that can see everything the rule needs. A verb with facts of its own becomes a class, such as a walk or a ticket. Say the rejections aloud.
- A noun stays for one of three reasons: identity, rule, or facts that travel together.
- Entities are equal by id, values by contents. Values do not change.
- A verb with facts of its own becomes a class.
- One owner per fact. Derive before you store.
- The owner of a rule is the smallest object that sees everything the rule needs. It may be missing from the text.
- Container, item and manager help you search. They are not class names.
Sources
- Beck and Cunningham: A Laboratory for Teaching Object-Oriented Thinking (1989)
- Martin Fowler: Evans classification
- Martin Fowler: Value object
- Martin Fowler: DDD aggregate
- Martin Fowler: Anemic domain model
- Django: extra fields on many-to-many relationships
- Pro Git: Git objects
- The Rust book: what is ownership