AlgoViz

Finding entities and owners

medium 35 min

A spec is full of nouns, and most of them are not classes.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:50

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

  1. 1976

    Peter Chen publishes the entity-relationship model: a world of things, and named relationships between them.

  2. 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.

  3. 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.

  4. 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.

Step 1 of 5

Underline. Nouns and verbs of the spec

Understand it

Casting a play
queenguardletterlanternnight

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
R1A volunteer can book a walk with a dog for a time slot on a day
R2Two walks of one dog must not overlap, and neither must two walks of one volunteer
R3A dog is walked at most twice a day
R4Each dog needs a level of experience (easy, strong, nervous), and the volunteer must have at least this level
R5A walk can be cancelled
R6Anyone can see the walks of a dog on a day, in order
Q1Several volunteers book by phone at the same time
OutLeashes, 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

NounVerdictWhyBecomes a class when
DogEntityWe follow one dog. Its level can changeIt is one
VolunteerEntityR2 and R4 need to know which one, and their levelIt is one
WalkRelationship with factsIt joins a dog and a volunteer, and has a slot and an id to cancelIt is one
Time slotValue objectDay, start and end mean something only together, and it can tell whether it overlapsIt is one, small and frozen
RotaOwnerNot in bold anywhere, but R2 and R3 are about all walks togetherIt is one
LevelEnumThree fixed words with an orderA level gets behaviour, such as a training plan
DayFieldOne fact, part of the slotIt owns something, such as a closing time
Twice a dayConstantA number in a ruleThe number depends on the dog: then a field
PhoneCallerIt calls bookIt owns state, such as a call to be returned
Office, leash, feedingOut of scopeNo sentence needs themA sentence arrives
Small dog, nervous dogNot classesThey differ in one value: the levelThey behave differently
The last column is worth saying aloud. It shows that the verdict follows from the spec and not from taste.

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

ProblemContainerItemManagerWhat the audition changes
Parking lotFloor, spotVehicle, ticketParkingSystemFloor is a number until it owns something. A spot holds a vehicle, and is itself held by a pool
ChessBoard, squarePieceGameControllerA square is a row and a column: a value. Call the manager Game
LibraryShelf, sectionBook, memberLibrarianA book is two things: a title and a copy. The librarian is a caller. The loan is missing
Dog shelterRotaWalkRotaContainer and manager are the same object here
ElevatorBuilding, shaft, floorCar, request, buttonDispatcherA floor is a number, and a button is a caller
Two more roles are about change: policy (which rule has versions) and lifecycle (which thing has states). They are in Which pattern, when.

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.

EntityValue object
Equal whenSame idSame contents
ChangesYes, through its ownerNo. Make a new one
SharedBy reference or id, with careFreely
In PythonClass with an id@dataclass(frozen=True)
In JavaClass, equals on the idrecord
In TypeScriptClass, compare idsreadonly fields and an equals method
ExamplesDog, ticket, game, machineSlot, 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.walks and volunteer.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.walks holds 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
WalkRota holds 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 ruleNeeds to seeOwner
A slot ends after it startsStart and endSlot, in its constructor
Two slots overlapTwo slotsSlot.overlaps
The level of a dogThe dogDog
Is this volunteer good enough?Both levelsVolunteer.can_handle(dog)
No overlap for dog or volunteerAll walks of the dayWalkRota
At most two walks a dayAll walks of the dog on the dayWalkRota
Which ids are usedAll walksWalkRota
Three of the seven rows need all walks. Only these belong to the rota. With all seven it would be a god class.

A fact with two owners drifts apart

The count can be worked out from the walks. Do not store it, or let one object own both.

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.

PairQuestionRelationshipIn code
Rota and walkRota closed: are walks of any use? NoOwnsThe rota creates and removes them
Rota and dogRota closed: the dog still livesHasDogs are passed in
Walk and dogThe walk needs to know whichUsesHolds a reference or an id
Walk and slotThe slot is part of the walk's factsOwns a valueA frozen field
Dog and volunteerDo they know each other? NoNoneOnly a walk joins them
Dog and levelOne of three wordsUsesAn 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

One walk has exactly one dog and one volunteer. If two volunteers may share a walk, this picture changes first.

Design

The same shelter, badly cast and well cast

Everybody gets a part, and one does all the work

Dog+ name: str+ walks_today: intVolunteer+ name: str+ walking: boolLeash+ colour: str

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)

Six boxes, one brain, and the most important noun is absent.

Few names, each with something to do

Dog+ id: str+ needs: LevelVolunteer+ id: str+ skill: Level+ can_handle(dog)«enum»LevelEASYSTRONGNERVOUS

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

What each class holds and does in detail is the next step: Class design.

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.

1 of 3

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.

Java
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);    }}
No spot is handed out twice, and still four things are wrong.
What is wrongWhat the driver seesBetter owner
Find and book are two stepsTwo gates find the same spot. The slower one hears Full in a lot with 400 free spotsA pool that finds and takes in one step
isOccupied and activeTickets both say who is parkedAfter a lost ticket they disagreeFree spots in the pool, open tickets in the lot
The new ticket is never put into the mapNobody can drive outThe lot writes it in the same method
Full is an exception, and money is a doubleA normal evening looks like a crash. Cents go missingReturn 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.

1 of 4

Method

Two roads, same boxes

RoadHowGood atWeak at
Nouns and verbsUnderline the specA start in one minuteMisses owners that nobody names, keeps too much
ResponsibilitiesFor each rule ask who should do it, one card per class with its helpersFinds owners, keeps classes aliveSlow without a spec
Life of a thingFollow one dog, one walk from start to endFinds states and linksMisses rules about many things
Tables firstDraw what would be storedCounts (one to many)Leads to classes without behaviour
In the round: nouns for one minute, then responsibilities for three.

Saying it in the room

  1. 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.

  2. Interviewer

    Why is a nervous dog not a subclass?

  3. 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.

  4. Interviewer

    And who checks for overlaps? The dog?

  5. 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.

  6. Interviewer

    Why not WalkManager?

  7. You

    Rota says what it holds, so reminders and printing clearly do not belong in it.

Four minutes by the clock

  1. 1

    Underline

    One minute. Nouns and verbs, aloud.

  2. 2

    Reject

    One minute. One reason each, in half a sentence.

  3. 3

    Owners

    One minute. For each rule: who can see all of it?

  4. 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