Loading
Loading
Foundations
How to get from a paragraph of requirements to a set of types that each do one thing.
By the end of this chapter
Take the requirements and underline every noun. That gives you candidates — not a design. Most will survive as types, some will turn out to be fields on other types, and a few will be concepts the brief mentions but the system never needs to represent.
Then, for each survivor, write one sentence: "X is the only thing that knows ___." The sentence is the test. If you cannot finish it, the type has no reason to exist yet. If you need "and" to finish it, you have found two types wearing one name.
Concept
A ParkingSpace is the only thing that knows whether it is occupied and what size vehicle it takes. A Garage is the only thing that knows which spaces exist. Neither sentence needs the other, which is why they are two types.
A type with five fields, five getters, five setters and no other methods is not really a type — it is a record with ceremony. That is fine when it genuinely is a record, like a Ticket that exists to be read. It is a problem when the behaviour that belongs to that data has drifted somewhere else, because now two places have to change together.
The tell is a method on class A that reads three fields from class B and computes something about B. That method usually belongs on B. Moving it is the single highest-value refactor in most first drafts.
| Smell | What it usually means |
|---|---|
| A class with only getters and setters | Its behaviour lives elsewhere |
| A method that mostly reads another object's fields | Wrong home for the method |
| A class named ...Manager or ...Helper | A responsibility nobody has named |
| A class nothing else references | It may not need to exist |
| Two classes that always change together | They may be one class |
Once you have types, the next question is who knows about whom. Three distinctions matter more than the rest, and a lot of confusion disappears when you can name them.
| Relationship | Means | If the owner is destroyed |
|---|---|---|
| Composition | The part belongs to the whole | The part goes too |
| Aggregation | The whole holds the part, but does not own it | The part survives |
| Association | One references the other | Both survive |
| Dependency | One merely uses the other transiently | Nothing is held |
A Garage composes its ParkingSpaces: the spaces exist because the garage does. A Playlist aggregates Songs: delete the playlist and the songs remain. A Ticket is associated with a Vehicle: neither owns the other. A Garage depends on a FeePolicy: it calls it and holds nothing permanent.
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for: