AlgoViz

UML class diagrams

easy 45 min

A 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

0:00 / 4:49

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

  1. 1994

    James Rumbaugh joins Grady Booch at Rational Software. They begin to merge their two drawing methods.

  2. 1997

    The Object Management Group adopts UML as a standard. Booch, Rumbaugh and Ivar Jacobson led the work.

  3. 2003

    Martin Fowler describes UML as sketch: draw to communicate, choose what matters, leave out the rest.

  4. 2005

    UML is also published as an international standard, ISO/IEC 19501.

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

Step 1 of 4

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.

Asha, Lee, Max and the pattern sheet
A coat with pockets!

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

Person+ name: String- age: int = 0# id: long+ speak(): void+ walk(): void- think(): voidTop: the name

1/3Name

Bold and centred. A singular noun: Person, not Persons and not PersonManager.

Every compartment except the name may be left away. A box with only a name is a correct class.

Locks

Four visibility marks

MarkNameWho may use itPictureJavaPythonTypeScript
+publicEverybodyA parkpublicno underscorepublic (default)
-privateOnly this classA diaryprivate__name, or _name by agreementprivate or #name
#protectedThis class and its subclassesA family secretprotected (also the package)_name by agreementprotected
~packageClasses in the same packageA key for the neighboursno keywordno such thingno such thing
UML has one meaning per mark, and languages differ a little. Java's protected also lets the package in. Python checks nothing: one underscore is a request. See Encapsulation.

Spelling

How a member is written

Text
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})
Name first, type after the colon: the other way round from Java, the same as Python and TypeScript.

Translate `private boolean isAdult(int age)` in four moves

  1. 1

    Split it

    Visibility private, result boolean, name isAdult, parameter int age.

  2. 2

    Mark

    private becomes -.

  3. 3

    Turn the parameter round

    int age becomes age: int.

  4. 4

    Result to the end

    - isAdult(age: int): boolean.

Special boxes

Interface, abstract class, enumeration

Three boxes with a word above the name

«interface»Payable+ calculatePay(): double+ processPayment(amount): boolean

1/3Interface

A promise without a body. Usually two compartments: the name and the operations.

The standard writes «enumeration», and marks abstract classes by an italic name or {abstract}. On a board, and here, «enum» and «abstract» are common and everybody understands them. Differences in depth: Interface vs abstract class.

Lines

Six ways to be connected

One pair for each line

teachesTeacherStudent

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

Two memory helps. Dashed is weaker than solid. Every triangle is hollow: only the composition diamond is filled.

From a line to code and back

LineSay it aloudIn the codeExample
Association ──>knowsA field. Both sides go on livingTeacher.students
Aggregation ◇──hasA field that is handed in from outsideDepartment(professors)
Composition ◆──owns, is made ofA field created inside, never given awayHouse builds its Rooms
Generalization ──▷is aextends, class Dog(Animal)Dog, Animal
Realization ╌╌▷keeps the promise ofimplementsCircle, Shape
Dependency ╌╌>uses for a momentParameter, local variable, result, new inside a methodprocessOrder(order)
Aggregation and composition have their own page: Aggregation vs composition. When unsure on a board, draw a plain association and say who owns what.

Which line between A and B?

Four questions decide it. The second to last is about meaning, not about code: both parts are fields.

How many

Multiplicity

Numbers at the line ends

Read it across: one course owns one or more lessons, and a lesson belongs to exactly one course. A student rents no locker or one.
WrittenMeansTypical code
1Exactly oneA field that is never empty, set in the constructor
0..1None or oneOptional, | None, nullable
* or 0..*Any numberA list or set, may be empty
1..*At least oneA list, and the constructor refuses an empty one
2..4Between two and fourA list with a check
The number stands next to the class that it counts. A lower bound of 1 is a rule, and some line of code must defend it.

Zoom

Three perspectives

The same customer, three times

placesCustomerOrder

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

Say which one you draw. Many arguments about a diagram are two people reading it at two levels.

Neighbours

What a class diagram cannot say

The same classes in time

Order of calls. The class diagram only says that Course may call Notifier.

One object over its life

Allowed moves. In the class diagram this is one field of type Status.

Which picture answers which question?

QuestionPicture
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