Why Model

Object-Oriented Design with UML

Course 1 ยท Chapter 1 ยท Why Model: Analysis, Design and UML

You can write code without drawing anything, and for a small script you should. But sooner or later you will join a project where nobody can say which part owns the loan rules, or you will have to explain your design to someone who will not read your code, or you will find, three weeks in, that two classes each assumed the other did the checking. A model is a cheap way to find those problems before they are expensive. This course teaches how to think a design through, and how to draw it using the Unified Modeling Language (UML) so that others can read it.

What was checked, and what was not
The two diagrams and the Python in this chapter were produced and run on this machine: Mermaid's command-line renderer (@mermaid-js/mermaid-cli 12.0.0, Mermaid 12.1.0, drawing with Chrome) made the SVGs shown, and the Python (3.14) ran with the output pasted. The UML version and date come from OMG's own page for the specification, which I read. Two things I did not re-read for this chapter and give from general knowledge: the list of the 14 diagram types, and the three "modes" of using UML, which I attribute below to Martin Fowler's book UML Distilled. PlantUML (needs Java, which is not installed here) arrives in chapter 2.

Analysis and Design: Two Questions

Object-oriented analysis asks what is the problem? It looks at the situation (a library lending books) and finds the things in it, the goals people have and the rules that apply, without deciding how software will do it. Object-oriented design asks what shape should the solution take? It decides which classes exist, what each is responsible for, and how they cooperate. In practice the two overlap and you go back and forth, but keeping the questions apart prevents a common failure: designing a clever solution to a problem nobody checked.

AnalysisDesign
QuestionWhat is the problem, in the user's world?How will the software be organised to solve it?
Typical outputUse cases, a domain model, a glossaryClass design, interactions, states, components
Who must understand itUsers and domain experts, as well as developersMainly developers
In this courseChapters 3 and 4Chapters 5 to 11

Requirements and design documents as parts of a whole project are covered in The Software Development Lifecycle 5 (Requirements & User Stories) and 8 (Design Documents & ADRs); this course is about the modelling skills inside those activities and does not repeat them.

What UML Is

UML is a standard, graphical vocabulary for describing software: boxes for classes, arrows for relationships, lifelines for objects exchanging messages. It is maintained by the Object Management Group (OMG). OMG's page for the specification lists UML 2.5.1, published December 2017, as the current formal version (2.0 was July 2005; 1.1, the first, December 1997). That page mentions no ISO number, so I make no claim about one. Its value is shared meaning: when you draw a hollow diamond, a reader who knows UML knows what you mean without asking.

Three Ways to Use UML

Martin Fowler's UML Distilled (from my memory of the book, not re-read) describes three modes, and knowing which one you are in settles most arguments about "how detailed should the diagram be":

ModeWhat it isPrecisionLifetimeExample
SketchDrawings to communicate an idea or explore oneLow: leave out whatever does not matterMinutes or days: thrown away, or redrawn when neededTwo developers at a whiteboard deciding how loans and reservations relate
BlueprintDetailed designs a team builds from, often by a designer for othersHigh: every operation and typeMonths, with a real risk of falling out of dateA full class design handed to another team
Programming languageModels complete enough to generate the programCompleteThe model is the sourceModel-driven tools (chapter 10 explains why this faded)

This course works almost entirely in sketch mode, with the sketches kept as text beside the code. That is where UML pays for itself in most teams: a quick shared picture, cheap to change. Detail beyond what the reader needs is not extra rigour, it is extra maintenance.

The Diagram Types

UML 2 defines 14 kinds of diagram, in two groups: structure (what exists) and behaviour (what happens). Interaction diagrams are a sub-group of the behaviour ones. This course teaches the ones you will actually draw:

GroupDiagramAnswersChapter
StructureClassWhat kinds of things exist, and how are they related?4, 5
StructureComponent, package, deploymentHow is the system divided up, and where does it run?9
StructureObjectWhat does one example snapshot look like?9
BehaviourUse caseWho uses the system, and for what goals?3
Behaviour (interaction)SequenceIn what order do objects exchange messages in one scenario?7
BehaviourState machineWhat states can one object be in, and what moves it between them?8
BehaviourActivityWhat are the steps of a workflow, including choices and parallel work?8

That covers nine of the fourteen: class, object, component, package, deployment (structure) and use case, sequence, state machine, activity (behaviour). The other five are composite structure, profile (structure) and communication, interaction overview, timing (behaviour). Communication diagrams get a paragraph in chapter 7; the rest are specialist tools you can learn from the specification the day you need one. Not learning them is a sensible choice, not a gap.

A First Taste: One Idea, Two Pictures

The library lending system runs through most of this course, so meet it now. A community library has members, books, and loans. Here is the idea as a structure diagram (a small class diagram) and as a behaviour diagram (a sequence diagram). Both are Mermaid text, rendered to SVG by the real tool. How to write and render them is chapter 2; for now, just read them.

borrows

1

0..*

of

*

1

Member

name

email

Loan

borrowedOn

dueOn

Book

title

isbn

Structure: a member borrows zero or more loans (the arrow means a member can reach their loans); each loan is of exactly one book. A book can appear in many loans over time (the *).

SystemLibrarianSystemLibrarianMemberhands over book and cardborrow(card, isbn)due date, or refusalbook and due dateMember

Behaviour: one scenario, "borrow a book", with a person, the librarian and the system. Time runs downwards; dashed arrows are replies.

Neither picture says anything about databases, screens or Python. That is the point of a sketch: it is about the problem and the cooperation, and you could argue about it with a librarian.

A Diagram Says Less Than Code, On Purpose

Here is the structure sketch turned into Python (run on this machine). Read the comments: they show where each line of the diagram went.

from dataclasses import dataclass, field from datetime import date, timedelta @dataclass class Book: title: str isbn: str @dataclass class Loan: book: Book # Loan "*" --> "1" Book borrowed_on: date due_on: date @dataclass class Member: name: str email: str loans: list[Loan] = field(default_factory=list) # Member "1" --> "0..*" Loan def borrow(self, book: Book, today: date) -> Loan: loan = Loan(book, today, today + timedelta(days=21)) self.loans.append(loan) return loan ada = Member("Ada", "ada@example.org") dune = Book("Dune", "978-0-00-000000-0") loan = ada.borrow(dune, date(2026, 10, 10)) print(f"{ada.name} has {len(ada.loans)} loan(s); {loan.book.title} is due {loan.due_on}")
Ada has 1 loan(s); Dune is due 2026-10-31

Look at what the code had to decide that the diagram never mentioned: that a loan lasts 21 days, that it is the member who creates it, that a loan keeps its book as an object rather than an id, and that borrow exists at all. The diagram was not wrong; it was silent. Some of those silences are decisions for later chapters (chapter 6 asks who should create a loan); some are rules you must go and ask a librarian about (is 21 days right?). Finding the silences is half the value of drawing. Chapter 10 returns to how diagrams and code map onto each other, and why they do not stay in step by themselves.

What UML Is Not

  • Not a process. UML says how to draw, not when, in what order, or by whom. It fits an agile team sketching on a whiteboard as well as a long, documented project.
  • Not code, and not automatically in sync with code. A diagram drawn last month describes last month. Keeping it honest is a choice you make (small diagrams, kept as text next to the code, regenerated where possible); there is no magic.
  • Not a measure of quality. A beautiful diagram can describe a poor design, and a messy sketch can describe a good one. Judging the design is its own skill (chapters 6 and 11).
  • Not the only notation. Boxes and arrows on a whiteboard, a table of responsibilities, or a paragraph can be better. Use UML where its shared meaning helps.

How Much Modelling Is Worth It?

There is no formula, but these questions give a useful answer:

  • Is the thing hard to change later? Relationships between your main concepts, the boundaries between components and the order of a tricky interaction are expensive to get wrong. The name of a private helper is not.
  • Is more than one person involved? A diagram is a conversation tool; for a one-person throwaway script it is overhead.
  • Is there something you do not yet understand? Drawing is a cheap way to discover it. If you can already see the whole design, writing the code is the faster check.
  • Who will maintain the diagram? If the answer is "nobody", keep it a sketch and date it, or do not keep it.

A good stopping rule: stop when the diagram answers the question you drew it for. Then go and test the idea in code. Design and code are two ways of finding out whether an idea works, and the second is more truthful; use the first to avoid the slow, expensive part of the second.

Mistakes while preparing this chapter
  • The first render was 190 KB per diagram. Mermaid's renderer embeds a web font into every SVG, which would have bloated the page and could have clashed between diagrams that share an element id. What went wrong: I accepted the tool's default output. Asking for a plain system font and a distinct --svgId for each diagram made each file about 25 KB and gave every diagram its own id. Takeaway: check the size and the ids of generated SVG before inlining it in a page.
  • Pale, unreadable diagram text on the dark page. The class diagram rendered fine in a PNG but, inlined, its labels were nearly invisible: Mermaid draws class-diagram text as HTML inside the SVG, which inherits the page's light text colour, on the diagram's white panel. The sequence diagram (SVG text) was fine, which is why only a screenshot of the real page showed it. Takeaway: look at the diagram in the page itself, on the real theme, not just in the tool's own output; the course stylesheet now sets a dark text colour on diagram panels.
  • My own count did not add up. A first draft of the diagram-types section said "the other seven" were not taught, but the table taught nine of fourteen, leaving five. What went wrong: I wrote the number from memory instead of counting the list. Takeaway: when a list must total a number, write all the items out and count them (here 5 structure and behaviour types left over, listed above).

Hands-On Exercises

Exercise 1

Classify five situations as sketch, blueprint or programming-language mode, and say what you would draw (and what you would leave out) in each: (a) deciding with a colleague how to split a billing feature; (b) handing a payment-gateway design to an outsourced team; (c) a new teammate's first-day explanation of the system; (d) a tool that generates code from the diagram; (e) a ten-line script you will run once.

๐Ÿ“„ View solution
Exercise 2

Draw a small structure sketch (Mermaid class diagram) for the library's reservation idea: a member places reservations, each holding a place for one book. Render it, and say what the multiplicities mean in words.

๐Ÿ“„ View solution
Exercise 3

Turn your reservation sketch into Python, run it, and find a rule the diagram does not state that the code allows to be broken. List the questions you would take to a librarian.

๐Ÿ“„ View solution

Chapter 1 Quick Reference

  • Analysis = what is the problem; design = what shape the solution takes; they overlap, but keep the questions apart
  • UML 2.5.1 (OMG, December 2017) is the current formal version per OMG's page; it is a notation, not a process or a quality measure
  • Three modes: sketch (this course), blueprint, programming language; the mode decides the detail
  • 14 diagram types; taught here: class, use case, sequence, state machine, activity, component/package/deployment, object
  • Diagrams say less than code, on purpose: the gaps are the questions to ask
  • Model what is hard to change, shared by several people, or not yet understood; stop when the diagram answers its question; then test in code
Coming next
Object-Oriented Design with UML 2 (Diagrams as Code): why text beats drag-and-drop, Mermaid and PlantUML compared, installing and rendering both for real, and keeping the sources next to your code.