Reading & Drawing Class Diagrams
A shop adds a "buy it again" button. Ana reorders last week's mug and lamp, raises the mugs to three on the new order, and last week's order changes too: both orders hold the very same line object. The class diagram said this could happen, if you know how to read it. This episode teaches you to read and draw class diagrams: the class box, all six arrows, multiplicity, and how every arrow maps to one line of real Python. Then we let pyreverse draw the diagram from the code, and compare it with ours, link by link.
Chapters
- 0:00 Intro
- 0:57 The idea in one sentence
- 1:39 Reading a class box
- 2:32 Association, and how many
- 3:14 The two diamonds
- 3:54 Dependency
- 4:20 Two triangles: inheritance and realization
- 5:00 Six arrows, one map
- 5:21 The change request
- 6:13 Test it
- 6:54 Hands-on: pyreverse draws it for you
- 7:39 What pyreverse can't know
- 8:24 The other way: diagram to code
- 9:03 Trade-offs: how much to draw
- 9:31 Where you've already met it
- 9:55 Interview corner
- 10:47 Recap and the road ahead
Cheat sheet
- Class box: name on top, attributes in the middle, operations at the bottom
- Visibility: + public, - private (a leading underscore in Python), # protected, ~ package
- Underlined: static (belongs to the class); a class name in italics: abstract
- Association: solid line, open arrowhead. One class keeps a reference to another
- Multiplicity: 1 exactly one, 0..1 optional, * any number, 1..* at least one
- Aggregation: hollow diamond on the whole. Parts made elsewhere, may be shared
- Composition: filled diamond on the whole. Parts owned by one whole, gone with it
- Dependency: dashed line, open arrowhead. Used, not kept (a parameter, a local, a call)
- Inheritance: solid line, hollow triangle, pointing at the more general type
- Realization: dashed line, hollow triangle. A class keeps an interface's promise
- Code shows what exists; the diamonds and the numbers show what you meant
- Generate the boxes with a tool; draw the arrows that matter yourself
Diagrams
- v1 · aggregation
- v2 · composition
- v3 · shipping (shipping diagram)
Code
Three versions of a small ordering module (Python 3.14, pytest, pylint 4.1.3 for pyreverse): version 1 with aggregation, where "buy it again" shares order lines (9 passed); version 2 with composition, where the order makes and owns its lines (12 passed, the price files and their tests untouched); and version 3, a shipment diagram turned into code (16 passed). Every class diagram is a Mermaid file next to the code.
check_tests_catch_the_bug.pycompare_diagrams.pyREADME.mdrun_pyreverse.pysave_outputs.pyv1_aggregation/class_diagram.mmdv1_aggregation/demo.pyv1_aggregation/lifetime.pyv1_aggregation/prices.pyv1_aggregation/shop.pyv1_aggregation/static_member.pyv1_aggregation/test_orders.pyv1_aggregation/test_prices.pyv2_composition/class_diagram.mmdv2_composition/demo.pyv2_composition/lifetime.pyv2_composition/prices.pyv2_composition/shop.pyv2_composition/test_orders.pyv2_composition/test_ownership.pyv2_composition/test_prices.pyv3_shipping/demo_shipping.pyv3_shipping/prices.pyv3_shipping/shipping.pyv3_shipping/shipping_diagram.mmdv3_shipping/shop.pyv3_shipping/test_orders.pyv3_shipping/test_ownership.pyv3_shipping/test_prices.pyv3_shipping/test_shipping.pywhat_changed.py
Sources
- UML 2.5.1, Object Management Group
- UML 1.4 specification (the history of UML)
- Pyreverse documentation
- Mermaid class diagrams
- Python dataclasses (frozen instances, replace, class variables)
- typing.Protocol
- PEP 544, Protocols
- weakref
- GitHub, creating diagrams
- IntelliJ IDEA, UML class diagrams
Transcript
Here's the ordering code from an online shop, and its class diagram. An order belongs to a customer, and holds order lines, each with a product, and a quantity. It works, and all nine tests pass. Then the shop adds a button: buy it again. Last week, Ana ordered a mug and a lamp, for sixty-two dollars.
Buy it again copies that order, and this week she wants three mugs, so the new order comes to eighty-six. Then she opens last week's order. It says eighty-six too. Both orders hold the very same line object, so changing one changes both. And the class diagram said this could happen, if you know how to read it.
So a change request arrives: an order line can't exist without its order.
This is Just Known. From unknown, to known. Episode three of our low-level design series: reading and drawing class diagrams. This whole episode, in one sentence: a class diagram is a map of your code, where every box is a class, and every arrow is a line of code. Six kinds of arrow cover nearly every class diagram you'll read.
Learn them, and you can point from any arrow to the line of code behind it. The notation is U M L, the Unified Modeling Language. By 1994, there were more than fifty object-oriented modeling languages. That October, Grady Booch and Jim Rumbaugh at Rational Software began merging their two methods, and Ivar Jacobson joined them in the fall of 1995. The Object Management Group adopted U M L in 1997, and it still looks after it.
Today's version is two point five point one. Start with one box: our order class, drawn from its code. The name goes on top. The middle holds its data, the attributes, each with its type after a colon. The bottom holds what it can do, which U M L calls operations, with their parameters and return types.
The mark in front of each member is its visibility. A plus sign means public. A minus sign means private: in Python, that's a leading underscore, like underscore lines. There's also a hash for protected, meaning open to subclasses, and a tilde for package. Two more marks.
Underlined means static: it belongs to the class, not to each object, like an order line's maximum quantity. And a class name in italics means abstract: like last episode's payment method, it can't be created on its own. Now the arrows. The first is association: a solid line with an open arrowhead. One class knows another, and keeps a reference to it, usually in an attribute.
An order keeps its customer. An order line keeps its product. The arrowhead shows which way you can navigate: an order knows its customer, but a customer doesn't keep a list of orders. The numbers at each end are multiplicity: how many. One means exactly one.
Zero dot dot one means optional. A star means any number, even none, and one dot dot star means at least one. So each order has exactly one customer, and a customer can have any number of orders. Some links are a whole and its parts. A diamond marks the whole.
A hollow diamond is aggregation, which U M L calls shared. In practice, it marks a whole that holds parts it doesn't own: they're made elsewhere, and can be shared, or outlive it. That's version one. Lines are made outside and handed in with add, and nothing stops one line from going into two orders. So the order's end of that diamond gets a star.
A filled diamond is composition, and here U M L is strict. A part belongs to at most one whole at a time, and when the whole is deleted, its parts normally go with it. That's our change request, word for word. The loosest link is dependency: a dashed line with an open arrowhead. One class uses another, but doesn't keep it.
Total takes the prices as a parameter, asks for each line's price, and lets them go. If the prices interface changes, total may have to change too. That's all a dependency says. In code, it's a parameter, a local variable, or a call. If you keep it in an attribute, it's an association.
Two arrows end in a hollow triangle, pointing at the more general type. On a solid line, it's inheritance: sale prices is a kind of price list. It inherits the lookup, and changes one thing: it takes a percentage off. On a dashed line, it's realization: a class keeps a promise that an interface makes. Python has no interface keyword.
In this series, an interface is a protocol, with method signatures and no code, and a class that names it as a base realizes it. Price list names the prices protocol, so it gets the dashed triangle. Python even checks the promise: a class that names prices, but skips price of, can't be created. That's all six. To keep them straight: a triangle points to the more general type.
A diamond sits on the whole. And the two dashed arrows are both dependencies: in U M L, realization is a special kind of dependency. Here's version one's whole diagram. Every arrow on it comes from one line of code. Now the change request: an order line can't exist without its order.
Version two makes the filled diamond true in code. The order makes its own lines: add line takes a product and a quantity, and builds the line inside. There's no method that takes a line from outside. Lines are frozen, so nobody can change one behind the order's back: to change a quantity, you ask the order, and it swaps in a new line. And buy it again copies each product and quantity, not the line.
Replay the cold open. This week comes to eighty-six, and last week stays at sixty-two. Different line objects now, and changing one from outside raises a frozen instance error. Lifetimes follow, too. A Python object lives while anything still refers to it.
Delete last week's order: in version one, its line lives on, inside this week's order. In version two, it's gone. On the diagram, one arrow changed: the diamond filled in, and the star on the order's end became a one. In the code, only the shop module changed. Prices, and their tests, are identical files.
There are twelve tests now. The five order tests are the same tests, with the same numbers: they just ask the order to make the lines. Three new tests guard the rule: buy it again never shares a line, nobody outside can change one, and a line goes when its order goes. All twelve pass. Run the three new tests against version one, even with an add line shortcut bolted on, and all three fail.
A method name isn't composition. Ownership is. Do you have to draw all of this by hand? Not the first draft. Pyreverse comes with Pylint.
It reads your code and writes a class diagram, here as Mermaid text. Run it on version one. It finds every class, with its public attributes and methods, and most of their types. It marks price of as abstract. It gets the inheritance from sale prices to price list right, and the line's association to its product.
But look closer. By default, it skips names that start with an underscore, so the order's lines aren't there, and neither is the link this whole episode is about. Ask for everything, and that link comes back as a plain association. And run it on version two: the links come out exactly the same. Here are both diagrams, link by link.
Two match. The others are guesses from syntax. A parameter stored in an attribute counts as aggregation, so the order aggregates its customer. A base class counts as inheritance, so the protocol becomes a parent class. A parameter that's only used isn't a link at all, so the dependency on prices is gone.
And there's no multiplicity anywhere. That's not a bug in pyreverse. Code shows what exists, not what you meant. Whether a line may be shared, how many there can be, which dependency matters: that's design intent, and it belongs in your diagram. So generate the boxes, and draw the arrows that matter yourself.
It works the other way, too. Say the warehouse team hands us this diagram, and we write the code it asks for. A shipment points to exactly one order: a required argument, kept in an attribute. The filled diamond says it makes its own parcels, and keeps them in a private list. One dot dot star means never empty, so the constructor takes the first parcel's weight.
And the underlined maximum weight is a class variable. Four tests hold the code to the diagram, and they pass. And pyreverse, run on this code, calls the order link aggregation, and finds no link to the parcels at all. So when is a class diagram worth drawing? Before you build anything with more than a few classes, in a design review, and in an interview.
Draw only what helps the reader: the classes and links that matter, not every method. And skip it for a small script, or throwaway code. A diagram that's out of date is worse than none. Keep it as text next to the code, like the Mermaid files in this episode's repo, so it changes in the same pull request. You've probably met these already.
GitHub draws Mermaid diagrams right inside Markdown files, issues and pull requests, so the diagram in this episode's readme draws itself. IntelliJ IDEA draws class diagrams from Java and Kotlin code, so they always match the code as it is. And every design pattern in this series, from episode nine on, starts as one of these diagrams. Interview corner. What's the difference between aggregation and composition?
And how would you show it in code? Pause here, and try answering in thirty seconds.
Here's a strong answer. Both are a whole and its parts, with the diamond on the whole. Aggregation, the hollow diamond, is a whole that holds parts it doesn't own: they're made elsewhere, can be shared, and can outlive it. Composition, the filled diamond, owns its parts: each belongs to one whole at a time, and goes when the whole goes. In code, the whole creates its parts, and never hands out a way to share or change them.
To stand out, give one example both ways, like an order and its lines, and say how you'd test it: copy an order, change the copy, and check the original. Let's recap. A class diagram is a map of your code: boxes for classes, and six arrows for how they relate, each one a line of code. The diamonds and the numbers carry intent that code can't show, so a tool can draw your boxes, but the meaning is yours to draw. Next, we'll watch these objects talk to each other, one call at a time.
That's episode four: sequence diagrams, how objects talk. This is Just Known. From unknown, to known.
Note: Ana, the mug, the lamp and the shop are made-up examples; every line of code, test and output on screen is from a real run (Python 3.14.3, pytest 9.2.0, pylint 4.1.3, astroid 4.3.4). Pictures marked "illustration" are not real output.
Narration voice generated with Google Gemini text-to-speech.
