UML class diagrams
easy 45 minA class diagram is a picture of the types in a program and the lines between them.
Chapter mnemonic
Read a sequence diagram
Name the actors. Follow the arrows. Read down the stage.
Which marks show who called whom, and where do you look for the next event?
Read the message arrows between participants, then move down the relevant lifeline.
Video lesson · Chapter 1 of 6
Make a prediction
UML class diagrams
1:02Reel
Theory
Read or listen first. About 2 min.
What it is
UML is the Unified Modeling Language: a set of agreed drawings for software. The class diagram is the most used of them. It shows the static structure: which classes exist, what each one knows and does, and which of them know each other.
Static means that it does not show time. A class diagram tells you that a course has lessons. It does not tell you when a lesson is added, or who calls first. Those questions belong to sequence and state diagrams.
A diagram is a selection. It leaves out most of the code on purpose. A good one answers one question, such as: where does the price live, and what must change when a new kind of price arrives?
Why it exists
A paragraph can be read in two ways, and a page of code takes long to read. A picture with agreed symbols is read in seconds, and two people who read it see the same thing.
It is cheap to change. Moving a method between two boxes takes a second. Moving it between two classes that are already used and tested takes an afternoon. So mistakes are found where they cost least.
In an object design interview the diagram is the thing you both look at. It shows the interviewer how you split the work before you spend twenty minutes on code.
A short history
1994
James Rumbaugh joins Grady Booch at Rational Software. They begin to merge their two drawing methods.
1997
The Object Management Group adopts UML as a standard. Booch, Rumbaugh and Ivar Jacobson led the work.
2003
Martin Fowler describes UML as sketch: draw to communicate, choose what matters, leave out the rest.
2005
UML is also published as an international standard, ISO/IEC 19501.
2017
Version 2.5.1 is published in December. It is the formal version on the OMG's page.
Words to know
- Class box
- A rectangle with up to three compartments: name, attributes, operations.
- Attribute
- What an object knows. In code: a field.
- Operation
- What an object can be asked to do. In code: a method.
- Visibility
- Who may use a member: + public, - private, # protected, ~ package.
- Stereotype
- A word in double angle brackets that says what kind of box it is, such as «interface».
- Association
- Objects of one class keep a link to objects of another.
- Aggregation
- Whole and part, where the part can live on. Hollow diamond at the whole.
- Composition
- Whole and part, where the part belongs to one whole and dies with it. Filled diamond at the whole.
- Generalization
- Is a. Solid line with a hollow triangle at the parent.
- Realization
- Keeps the promise of an interface. Dashed line with a hollow triangle.
- Dependency
- Uses it for a moment, for example as a parameter. Dashed line with an open arrow.
- Multiplicity
- How many objects may stand at that end of a line: 1, 0..1, *, 1..*.
- Navigability
- An arrow head that says from which side the link can be followed.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Find the nouns. Which things have their own rules or change over time?
Understand it
Start here
A coat described in words
A class diagram does for code what a pattern sheet does for clothes. Asha wants two equal coats. Lee and Max will each sew one.
Frames 1 and 2 are life without a diagram, 3 to 6 add names, lines and numbers, and 7 is the mistake of the diligent.
The box
Three compartments
One class, read from top to bottom
1/3Name
Bold and centred. A singular noun: Person, not Persons and not PersonManager.
Locks
Four visibility marks
| Mark | Name | Who may use it | Picture | Java | Python | TypeScript |
|---|---|---|---|---|---|---|
+ | public | Everybody | A park | public | no underscore | public (default) |
- | private | Only this class | A diary | private | __name, or _name by agreement | private or #name |
# | protected | This class and its subclasses | A family secret | protected (also the package) | _name by agreement | protected |
~ | package | Classes in the same package | A key for the neighbours | no keyword | no such thing | no such thing |
protected also lets the package in. Python checks nothing: one underscore is a request. See Encapsulation.Spelling
How a member is written
attribute: visibility name: Type [multiplicity] = defaultoperation: visibility name(parameter: Type, ...): ReturnTypepublic int age = 21 -> + age: int = 21private String name -> - name: Stringprivate List<String> phones -> - phones: String [0..*]public void setName(String n) -> + setName(n: String): voidprivate boolean isAdult(int age) -> - isAdult(age: int): booleanpublic static int count() -> + count(): int (underlined)public abstract void makeSound() -> + makeSound(): void (italic, or {abstract})Translate `private boolean isAdult(int age)` in four moves
- 1
Split it
Visibility
private, resultboolean, nameisAdult, parameterint age. - 2
Mark
privatebecomes-. - 3
Turn the parameter round
int agebecomesage: int. - 4
Result to the end
- isAdult(age: int): boolean.
Special boxes
Interface, abstract class, enumeration
Three boxes with a word above the name
1/3Interface
A promise without a body. Usually two compartments: the name and the operations.
Lines
Six ways to be connected
One pair for each line
1/6Association
A teacher keeps a list of students. A solid line. The arrow says that the teacher can reach the students.
useshas (lives on)owns (dies together)extends (is a)implementsdepends on
From a line to code and back
| Line | Say it aloud | In the code | Example |
|---|---|---|---|
Association ──> | knows | A field. Both sides go on living | Teacher.students |
Aggregation ◇── | has | A field that is handed in from outside | Department(professors) |
Composition ◆── | owns, is made of | A field created inside, never given away | House builds its Rooms |
Generalization ──▷ | is a | extends, class Dog(Animal) | Dog, Animal |
Realization ╌╌▷ | keeps the promise of | implements | Circle, Shape |
Dependency ╌╌> | uses for a moment | Parameter, local variable, result, new inside a method | processOrder(order) |
Which line between A and B?
How many
Multiplicity
Numbers at the line ends
| Written | Means | Typical code |
|---|---|---|
1 | Exactly one | A field that is never empty, set in the constructor |
0..1 | None or one | Optional, | None, nullable |
* or 0..* | Any number | A list or set, may be empty |
1..* | At least one | A list, and the constructor refuses an empty one |
2..4 | Between two and four | A list with a check |
Zoom
Three perspectives
The same customer, three times
1/3Conceptual
Words of the business. Names and lines, no members, no thought of a language. For the first ten minutes and for people who do not program.
uses
Neighbours
What a class diagram cannot say
The same classes in time
One object over its life
Which picture answers which question?
| Question | Picture |
|---|---|
| Which types exist, who knows whom, who owns what? | Class diagram |
| Who calls whom, in which order? | Sequence diagram |
| What may happen to one object? | State diagram |
| Which objects exist right now, with which values? | Object diagram (our Visualize page) |
| Which services and databases run where? | Architecture diagram, not UML classes |
Judgement
How much to draw
Sketch
To talk and think. Selected parts, loose notation, thrown away afterwards. The normal case.
Blueprint
Complete enough that somebody else writes the code from it. Rare, and expensive to keep up to date.
Programming language
Code is generated from the model. Used in some embedded and safety work, seldom elsewhere.
Map of old code
Generated from the code by a tool, to find the way in an unknown project.
A diagram that helps
- Three to eight boxes
- One question, written above it
- Every line can be said as a sentence
- Numbers at the ends where one or many matters
- Left out: getters, constructors, strings
A diagram that hides
- Every class of the package
- All getters and setters
- Diamonds everywhere, chosen by feeling
- Lines that cross and labels that lie on boxes
- No date and no link to the code
You have five minutes to show a design on a shared screen. What do you draw?
BreaksAll classes with all members
- How
- Type every field and method of twelve classes into a tool.
- Limit
- The five minutes are over, and nobody knows where to look.
- Choose when
- Never in a conversation.
WorksNames and plain lines
- How
- Six boxes, six lines, no members.
- Limit
- Good for finding the parts. It does not show where the logic lives.
- Choose when
- The first two minutes.
StrongNames first, then the members that decide
- How
- Six boxes, numbers at the ends, and only the two or three operations that the requirement asks about, each in the box that has the data.
- Limit
- You must choose, and say what you left out.
- Choose when
- Interviews and reviews.
Summary
The whole topic in one minute.
Box: name, what it knows, what it does. Marks: plus, minus, hash, tilde. Lines: solid is a lasting link, dashed is a promise or a short use. Triangles point at the more general type. Diamonds sit at the whole.
Draw for one question. Put the three to six classes that answer it on the board, write how many at the line ends, and say the sentence that each line stands for. If you cannot say it, the line is wrong.
- Three compartments: name, attributes, operations. Only the name is required.
- + public, - private, # protected, ~ package.
- Name first, type after the colon.
- Solid: lasting link. Dashed: promise or short use.
- Hollow triangle at the general type. Diamond at the whole: hollow lives on, filled dies too.
- Numbers at the ends are rules that code must defend.
- Draw for one question, at one perspective, and say every line aloud.
Sources
- OMG: Unified Modeling Language 2.5.1 (December 2017)
- Martin Fowler: UML as sketch (2003)
- Martin Fowler: UML mode
- Unified Modeling Language, history
- Class diagram
- Mermaid: class diagrams
- GitHub: creating diagrams
- PlantUML: class diagram
- IntelliJ IDEA: UML class diagrams
- Visual Studio: Class Designer
- Pylint: pyreverse
- Doxygen: graphs and diagrams
- django-extensions: graph models
- C4 model: code diagram
- Eclipse Papyrus