Skip to content

UML in Practice: Class, Sequence, State, Activity, Component, Package & Deployment Diagrams ​

"The objective of UML is to provide system architects, software engineers, and software developers with tools for analysis, design, and implementation of software-based systems as well as for modeling business and similar processes." — Object Management Group, OMG Unified Modeling Language Version 2.5.1 (formal/2017-12-05), Clause 1 "Scope", December 2017

Summary: UML is a standard picture language for software: 14 diagram types, half for structure (what exists) and half for behaviour (what happens over time). In daily work you need about seven of them, drawn as sketches, kept as text in the repository. Focus: The 14 diagrams and when each one answers a real question; class-diagram notation in depth (visibility, multiplicity, the six relationship lines, association classes, qualifiers, stereotypes, OCL); sequence, state machine and activity notation; component, package and deployment views; Fowler's three modes; PlantUML and Mermaid; the C4 model; reading Go and Laravel code into diagrams. Learning goal: Pick the right diagram for a design question, draw it correctly in five minutes as PlantUML or Mermaid text, read any UML a colleague hands you, and keep the diagrams honest by generating or testing them against Go and Laravel code.

This page is the complete reference for UML as working engineers use it. It covers the history (Booch, Rumbaugh, Jacobson and the OMG), all 14 diagram types of UML 2.5.1, the notation details that cause most misreadings, Fowler's sketch/blueprint/programming-language split, text-based UML with PlantUML and Mermaid, the C4 model as the modern complement for architecture, and one checkout system drawn six ways and implemented in Go and Laravel. It does not re-teach its neighbours: the difference between architecture and design is on Architecture vs Design, CRC cards and conceptual design on The Design Process, the object-oriented ideas behind every box on Object-Oriented Modeling, class responsibilities on Low-Level Design, and the pattern diagrams on Design Patterns. Interfaces as seams are on Interface Segregation and Dependency Inversion.

Page map ​

If you are looking forGo to
All 14 diagrams and the three relationship tables on one screenEverything in one minute
Why a standard notation exists and what it costsWhy UML exists
Booch, OMT, OOSE, the OMG, UML 1.x to 2.5.1Where it comes from
Sketch vs blueprint vs programming languageFowler's three modes
Structure vs behaviour taxonomyThe 14 diagrams
Visibility, multiplicity, arrows, association classes, qualifiers, stereotypes, OCLClass diagram
Object, package, component, composite structure, profile, deploymentStructure diagrams
Use case, activity, state machineBehaviour diagrams
Sequence, communication, interaction overview, timingInteraction diagrams
Frames, metamodel, XMI, text syntaxesMechanics
Turning a Go package or a Laravel module into a class diagramReading Go, Reading Laravel
Checkout drawn six ways and coded in Go and LaravelGo, Laravel, Worked system
UML vs C4, and which diagram for which questionUML and C4, Choosing
Diagrams for monoliths, modules, services and replicasIn architecture
Hands-on: generate, render and test diagramsLab
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The 14 diagrams of UML 2.5.1. The list is Annex A of the specification; "used daily" is our judgement from practice, not the spec's.

DiagramFamilyQuestion it answersUse it whenUsed daily?PlantUML / Mermaid
ClassStructureWhat types exist and how are they related?Domain model, module API, review of a designYesYes / Yes
ObjectStructureWhat does memory look like at one moment?Explaining a tricky data shape, test fixturesSometimesYes / No
PackageStructureWhich modules depend on which?Layering, import rules, modular monolithYesYes / via flowchart
ComponentStructureWhich replaceable parts provide and require which interfaces?Ports and adapters, plug-in boundariesYesYes / via flowchart or C4
Composite structureStructureWhat is wired inside one class or component?Embedded systems, parts and portsRarelyPartial / No
DeploymentStructureWhat runs where, and how do machines talk?Infrastructure, environments, failoverYesYes / via C4Deployment
ProfileStructureWhich stereotypes extend UML for my domain?Tool vendors, SysML-style extensionsRarelyNo / No
Use caseBehaviourWho uses the system for which goal?Scope workshops (text matters more)RarelyYes / No
ActivityBehaviourWhat steps happen, in which order, by whom, in parallel?Business workflows, pipelines, sagasYesYes / via flowchart
State machineBehaviourWhich states can one thing be in, and what moves it?Orders, payments, subscriptions, protocolsYesYes / Yes
SequenceInteractionWho calls whom, in what order, for one scenario?API flows, debugging, code reviewYesYes / Yes
CommunicationInteractionWho talks to whom (numbered messages on links)?Small collaborations on a whiteboardRarelyNo / No
Interaction overviewInteractionHow do several interactions chain together?Long scenarios built from sequence fragmentsRarelyNo / No
TimingInteractionHow do states change against a time axis?Real-time and hardware, timeoutsRarelyYes / No

The six class-diagram lines. Every row is unpacked in the class diagram block.

RelationshipLinePlain wordsPlantUML / MermaidTypical code
AssociationSolid line, optional open arrowA has a long-lived reference to BA --> BField holding B or B's id
AggregationSolid line, hollow diamond at the wholeB is part of A but can be shared or outlive itA o-- BSlice of pointers to shared things
CompositionSolid line, filled diamond at the wholeA owns B; B dies with AA *-- BSlice of values; ON DELETE CASCADE
DependencyDashed line, open arrowA uses B briefly (parameter, local, creation)A ..> BFunction argument, new B()
GeneralizationSolid line, hollow triangle at the parentA is a kind of BA --|> Bextends; Go embedding is not this
RealizationDashed line, hollow triangle at the interfaceA implements interface BA ..|> BPHP implements; Go implicit

Sequence-diagram arrows.

MessageLine and head (UML 2.5.1, 17.4.4)PlantUMLMermaid
Synchronous callSolid line, filled headA -> BA->>B
Asynchronous signal or callSolid line, open headA ->> BA-)B
ReplyDashed lineB --> A or returnB-->>A
CreateDashed line, open head, to the new lifeline's headcreate B then A -> Bcreate participant B
DeleteMessage ending in an X on the lifelinedestroy Bdestroy B
Lost / foundBlack dot at the end / at the startA ->x B (lost), [o-> B (found)not supported

Why UML exists ​

A design you cannot show is a design only you can review. Before 1997 every object-oriented method had its own boxes and arrows, so a diagram from one team needed a legend for the next. UML fixed the notation so that a filled diamond means the same thing in every book, tool and code review. The trade is the usual one: a shared language is more precise and more to learn.

Ad hoc boxes and linesUMLC4 model
Zero learning costA real learning cost (the spec is 796 pages)Small learning cost
Every arrow needs a legendArrows have fixed meaningsArrows are labelled relationships
Mixes levels (a class next to a server)Separates views by diagram typeSeparates views by zoom level
Cannot be checked against codeCan be generated from code and testedCode level often generated
Good for one meetingGood for design reviews and teachingGood for architecture documentation
UML DiagramStructure diagrams (7)Behavior diagrams (7)ClassObjectPackageComponentComposite StructureDeploymentProfileUse CaseActivityState MachineInteraction diagramsSequenceCommunicationInteraction OverviewTiming= the seven used most in practiceSource: OMG UML 2.5.1 (formal/2017-12-05), Annex A, Figure A.5

The analogy we reuse on this page: a building's drawing set. One house has a floor plan, an electrical plan, a plumbing plan and a site plan. Nobody draws one picture with every wire and pipe; each drawing answers one question for one reader, and all of them describe the same building. UML is that drawing set for software: the class diagram is the floor plan, the sequence diagram is "what happens when someone rings the bell", the deployment diagram is the site plan. The symbols are standard so that an electrician from another city can read them.

Three common misunderstandings, up front ​

  1. "UML is a heavyweight process." UML is a notation. The heavy process that came with it in the 1990s (the Rational Unified Process) is a separate thing. A two-minute whiteboard sketch with correct arrows is UML.
  2. "A diagram must show everything." The spec itself says the opposite for multiplicity: "If no multiplicity is shown on the diagram, no conclusion may be drawn about the multiplicity in the model." A diagram is a view of a model; leaving things out is normal.
  3. "UML is dead, use C4 instead." C4 covers static architecture structure at four zoom levels and its own FAQ says to "supplement the C4 diagrams with UML state diagrams, timing diagrams, etc if you need to". Sequence diagrams and state machines have no C4 replacement.

Where it comes from ​

The specification states the origin in its first clause:

"The initial versions of UML (UML 1) originated with three leading object-oriented methods (Booch, OMT, and OOSE), and incorporated a number of best practices from modeling language design, object-oriented programming, and architectural description languages." — OMG UML 2.5.1, Clause 1

The three methods belonged to the people later called the "three amigos": Grady Booch (the Booch method), James Rumbaugh (OMT, the Object Modeling Technique) and Ivar Jacobson (OOSE, Object-Oriented Software Engineering, which introduced use cases). Fowler's book page summarises why it mattered:

"The UML appeared in 1997 to eliminate the bedlam that had overtaken graphical modeling languages in the object-oriented world." — Martin Fowler, UML Distilled book page, martinfowler.com

YearEventSource
1994Rational Software hires James Rumbaugh; Booch and OMT merge workWikipedia (secondary)
1995Ivar Jacobson joins Rational; OOSE and use cases come inWikipedia (secondary)
Jan 1997UML Partners propose UML 1.0 to the OMGWikipedia (secondary)
Nov 1997OMG adopts UML 1.1Wikipedia (secondary)
1997Fowler's UML Distilled, the first UML bookFowler's book page
2003UML Distilled 3rd edition rewritten for UML 2Fowler's book page
2005UML 2.0 replaces 1.5; ISO/IEC 19501:2005 publishedWikipedia (secondary)
2012ISO/IEC 19505-1:2012 (UML 2 infrastructure)Wikipedia (secondary)
Dec 2017UML 2.5.1, OMG document formal/2017-12-05 (current)OMG spec cover page

UML 2.0 added the interaction operators (alt, opt, loop, par, ref) that make sequence diagrams useful, and UML 2.5 rewrote the text for readability: "The UML Infrastructure no longer forms part of the UML specification. The entire UML specification is constituted in this document." The same clause drops the old compliance levels L0 to L3: "A tool either complies with the whole of UML or it does not." The OMG's own list of published versions runs 1.5, 2.0, 2.1.2, 2.2, 2.3, 2.4.1, 2.5.1. The constraint language that sits beside UML, OCL, is a separate OMG specification; its page states that "OCL version 2.4 is the latest version of OCL that is aligned with UML 2.4.1 and MOF 2.4.1."

Two later threads matter for practitioners. Text-based UML (PlantUML, then Mermaid) moved diagrams into source control, and GitHub now renders Mermaid in Markdown. And Simon Brown's C4 model, which its FAQ says "was inspired by UML and the 4+1 model for software architecture", gave teams a lighter way to draw architecture; Kruchten's 4+1 views is the architecture-side ancestor.

Fowler's three modes: sketch, blueprint, programming language ​

Fowler's 2003 bliki entry explains why people argue about UML: "people differ about what should be in the UML because there are differing fundamental views about what the UML should be." He names three modes.

ModeGoalFowler's wordsToolsWhere it lives today
SketchCommunicate one idea, fast"The essence of sketching is selectivity."Whiteboard, PlantUML, MermaidDesign reviews, PRs, docs
BlueprintHand a complete design to coders"a UmlMode that focuses on completeness"CASE tools, round-trip engineeringRegulated and safety-critical domains
Programming languageGenerate the program from the model"I don't believe that graphical programming will succeed just because it's graphical."MDA, executable UMLNiche (embedded, some state-machine code generators)

"Hence my sound-bite “comprehensiveness is the enemy of comprehensibility”" — Martin Fowler, UmlAsSketch, bliki

Each mode works in two directions. Forward engineering draws before coding; reverse engineering draws from existing code to understand it. Blueprint tools that do both are round-trip tools; Fowler calls tools that use the source code itself as the repository "tripless". This page is written for the sketch mode, with one blueprint habit borrowed: keep the sketch as text next to the code and test it, so it cannot silently rot.

The concepts, one by one ​

Each block follows the same order: plain words, the usual wrong belief, a precise definition (quoted from UML 2.5.1 where the wording matters), a sequence or scenario, real situations, the notation, and the diagram as PlantUML and Mermaid text. The running example is one checkout: a customer places an order, stock is reserved, the card is charged, the order is paid and shipped.

The 14 diagrams: structure vs behaviour Must-know ​

In plain words: structure diagrams are photographs (what exists); behaviour diagrams are films (what happens). Interaction diagrams are the films about messages.

Common misunderstanding: "Every system needs all 14." The spec calls the taxonomy "a logical organization" and adds that "the boundaries between the various kinds of diagram types are not strictly enforced." Most teams use seven, and most single designs need two or three.

Definition: UML 2.5.1 Annex A: "Structure diagrams show the static structure of the objects in a system. That is, they depict those elements in a specification that are irrespective of time." And: "Behavior diagrams show the dynamic behavior of the objects in a system, including their methods, collaborations, activities, and state histories."

text
     Design question                                  First diagram    Second diagram
1    "What is an Order made of?"                       class            object (one example)
2    "What happens when the customer clicks Pay?"     sequence         activity (if many actors)
3    "Can a shipped order be canceled?"                state machine    -
4    "Which module may import which?"                 package          component
5    "What runs on which server?"                     deployment       C4 container

Real scenario: a design review for a refund feature needs a state machine (is "refunded" reachable from "shipped"?) and a sequence diagram (who calls the PSP, who emits the event); nobody needs a use case diagram. An onboarding document needs one C4 container diagram and one class diagram of the core domain.

Diagram frames. Annex A lets any diagram sit in a frame whose heading is [<kind>]<name>[<parameters>], with the short kinds act, cmp, dep, sd, pkg, stm, uc (and long forms such as class). When you see sd PlaceOrder in a corner, it is a sequence diagram named PlaceOrder.

Class diagram Must-know ​

In plain words: boxes are types, compartments list what they hold and what they can do, and the line style between two boxes says how they are related.

Common misunderstanding: "The diamond means 'has a'." Every association means "has a". The hollow diamond (aggregation) adds almost nothing; the spec says "Precise semantics of shared aggregation varies by application area and modeler." Only the filled diamond (composition) has a strong, testable meaning.

Definition: a class symbol is a rectangle with a name compartment and optional attribute and operation compartments. Attributes follow the property grammar of clause 9.5.4: [<visibility>] ['/'] <name> [':' <prop-type>] ['[' <multiplicity-range> ']'] ['=' <default>] ['{' <prop-modifier> [',' <prop-modifier>]* '}'], with <visibility> ::= ‘+’ | ‘-‘ | ‘#’ | ‘~’ (quote marks normalised in the property line).

«entity»Order+ id : OrderId {readOnly}- status : OrderStatus = Pending# placedAt : DateTime [0..1]~ lines : OrderLine [1..*] {ordered}+ /total : Money+ addLine(sku : String, qty : Integer) : void+ fire(e : Event) : Boolean+ {static} create(c : CustomerId) : Order- recalc() : void+ public · - private · # protected · ~ package/ derived · [m..n] multiplicity · {…} constraintunderline or {static} = static; italic name = abstractABAssociationA knows B (navigable to B)PlantUML/Mermaid: -->ABAggregationB is part of A, may be sharedPlantUML/Mermaid: o--ABCompositionA owns B; B dies with APlantUML/Mermaid: *--ABDependencyA uses B (temporary, «use»)PlantUML/Mermaid: ..>ABGeneralizationA is a kind of BPlantUML/Mermaid: --|>ABRealizationA implements interface BPlantUML/Mermaid: ..|>10..*Spec: hollow diamond = shared, filled = composite (11.5.4); dashed arrow = Dependency (7.7.4); hollow triangle = Generalization (9.2.4)

Visibility.

SymbolUML nameJava / C#PHPGo
+publicpublicpublicExported identifier (capital letter)
-privateprivateprivateNo equivalent per type
#protectedprotectedprotectedNo equivalent (no inheritance)
~packagepackage-private (Java)No equivalentUnexported identifier: visible in the whole package

Multiplicity. Written [lower..upper] on a property or at an association end; * means unbounded; omitted means "not shown", not "one" on a diagram, although in the attribute grammar an omitted multiplicity "implies a multiplicity of 1 (exactly one)".

WrittenMeansTypical code
1Exactly oneNon-null field
0..1OptionalNullable field, pointer, ?Type
* or 0..*Any numberSlice, collection, hasMany
1..*At least oneCollection plus a validation rule
2..4BoundedDomain rule (e.g. 2 to 4 players)
{ordered}, {unique}, {readOnly}Property modifiersSorted slice, set, immutable field

The six relationships. Spec wording, per line: a Dependency "is shown as a dashed arrow between two model Elements"; "A Realization is shown as a dashed line with a triangular arrowhead at the end that corresponds to the realized Element"; a Generalization "is shown as a line with a hollow triangle as an arrowhead"; and for associations, "When one end has aggregation = AggregationKind::shared a hollow diamond is added", while composition "differs in having the diamond filled in". The meaning of composition:

"Composite aggregation is a strong form of aggregation that requires a part object be included in at most one composite object at a time. If a composite object is deleted, all of its part instances that are objects are deleted with it." — OMG UML 2.5.1, 9.5.3

PlantUML's documentation compresses it to "The part cannot exist without the whole" (composition) and "The part can exist independently of the whole" (aggregation). Navigability is an open arrowhead on an association end; "A small x on the end of an Association indicates the end is not navigable."

Association class. When the link itself has data, the link is a class. The spec: "An AssociationClass is shown as a Class symbol attached to the Association path by a dashed line." Classic examples: Enrollment between Student and Course (grade, date); OrderLine between Order and Product (quantity, price at time of sale). In a relational database it becomes a join table with extra columns; in Laravel, a belongsToMany with withPivot('qty', 'unit_price') or a custom pivot model.

Qualified association. A qualifier is a small box on one end that acts like a map key: Order [lineNo] → 0..1 OrderLine reads "given an order and a line number, there is at most one line". The spec: a qualified end "has qualifiers that partition the instances associated with an instance at that end". In code it is a map, or a composite unique key (order_id, line_no).

Abstract, interface, enumeration, stereotypes. "The name of an abstract Classifier is shown in italics, where permitted by the font in use" (or with {abstract}). An interface uses the keyword «interface»; an enumeration «enumeration»; a data type «dataType». A stereotype such as «entity», «control», «boundary» or «repository» is a profile extension that tags an element with a role; keywords in guillemets that UML itself defines (like «interface» or «use») are not stereotypes but are drawn the same way.

Constraints and OCL. Anything in braces is a constraint: {qty > 0}, {ordered}, {xor}. Precise constraints can be written in OCL, for example:

text
context Order
  inv atLeastOneLine: self.lines->notEmpty()
  inv totalMatches:   self.total = self.lines->collect(subtotal)->sum()
context Order::fire(e : Event)
  pre:  e = Event::stockReserved implies self.lines->notEmpty()

In practice OCL appears in model-driven tooling; in code the same rules become validation, database CHECK constraints and tests.

Real scenario: a domain review of Order/OrderLine/Product where the composition question ("can a line exist without its order?") decides the foreign key's ON DELETE rule; a Laravel module review where an interface plus realization shows that StripeGateway can be swapped; a code review where an inheritance triangle reveals a Square extends Rectangle Liskov problem.

The checkout's full class diagram is drawn in the worked system; here is its text:

text
@startuml
hide circle
class Customer {
  - id : CustomerId
  - email : String
}
class Order <<entity>> {
  - id : OrderId
  - status : OrderStatus
  + /total : Money
  + addLine(sku, qty, price)
  + fire(e : Event)
}
class OrderLine {
  - sku : String
  - qty : Integer {qty > 0}
  - unitPrice : Money
  + /subtotal() : Money
}
class Product {
  - sku : String
  - price : Money
}
enum OrderStatus {
  Pending
  Reserved
  Paid
  Shipped
  Canceled
}
abstract class Payment {
  - amount : Money
}
class CardPayment
class WalletPayment
interface PaymentGateway {
  + charge(o, amt)
}
class StripeGateway
class CheckoutService <<control>> {
  + placeOrder(cmd)
}
Customer "1" -- "0..*" Order
' qualifier syntax from PlantUML's "Qualified associations" section
Order [lineNo] *-- "0..1" OrderLine : lines
OrderLine "0..*" --> "1" Product
Order --> OrderStatus : status
Order "1" -- "0..*" Payment
Payment <|-- CardPayment
Payment <|-- WalletPayment
CheckoutService ..> Order : <<create>>
CheckoutService ..> PaymentGateway : <<use>>
PaymentGateway <|.. StripeGateway
@enduml
mermaid
classDiagram
  class Customer {
    -CustomerId id
    -String email
  }
  class Order {
    <<entity>>
    -OrderId id
    -OrderStatus status
    +total() Money
    +addLine(sku, qty, price)
    +fire(Event e)
  }
  class OrderLine {
    -String sku
    -int qty
    -Money unitPrice
    +subtotal() Money
  }
  class OrderStatus {
    <<enumeration>>
    Pending
    Reserved
    Paid
    Shipped
    Canceled
  }
  class Payment {
    <<abstract>>
    -Money amount
  }
  class PaymentGateway {
    <<interface>>
    +charge(o, amt)
  }
  Customer "1" -- "0..*" Order
  Order "1" *-- "1..*" OrderLine : lines
  OrderLine "0..*" --> "1" Product
  Order --> OrderStatus : status
  Order "1" -- "0..*" Payment
  Payment <|-- CardPayment
  Payment <|-- WalletPayment
  CheckoutService ..> Order : create
  CheckoutService ..> PaymentGateway : use
  PaymentGateway <|.. StripeGateway
  %% Mermaid has no qualifiers and no derived (/) marker

Object diagram Good to know ​

In plain words: a photograph of memory: concrete objects with values, linked to each other, at one instant.

Common misunderstanding: "An object diagram is a class diagram with different names." It shows instances, so multiplicities become actual counts and you can see the case that breaks a rule (an order with zero lines, two customers sharing one cart).

Definition: an object is an InstanceSpecification: "An InstanceSpecification represents the possible or actual existence of instances in a modeled system". It is drawn like a class with the name underlined as name : Type, and slots attribute = value.

text
     Moment   Object state (after PlaceOrder succeeded)
1    t0       c7:Customer  --  o1:Order{status=pending}
2    t1       o1 *-- l1:OrderLine{lineNo=1, qty=2}, l2:OrderLine{lineNo=2, qty=1}
3    t2       o1{status=paid, /total=33.00 EUR}

Real scenario: explaining a recursive structure (a category tree, a bill of materials); documenting a test fixture; showing support engineers exactly what a broken production record looked like.

Object diagram (a snapshot)Communication diagramc7 : Customeremail = "a@b.io"o1 : Orderid = "o-1"status = paid/total = 33.00 EURl1 : OrderLinelineNo = 1sku = "BOOK-1"qty = 2l2 : OrderLinelineNo = 2sku = "PEN-9"qty = 1:Client:CheckoutService:Inventory:PaymentGateway:OrderRepo:Broker1: placeOrder()1.1: reserve()1.2: charge()1.3: save()1.4: publish()Message order lives in the numbers, not the layout.Underlined name : Type = an instance; slots hold values.
text
@startuml
object "c7 : Customer" as c7 {
  email = "a@b.io"
}
object "o1 : Order" as o1 {
  id = "o-1"
  status = paid
}
object "l1 : OrderLine" as l1 {
  lineNo = 1
  qty = 2
}
object "l2 : OrderLine" as l2 {
  lineNo = 2
  qty = 1
}
c7 -- o1
o1 *-- l1
o1 *-- l2
@enduml
mermaid
%% Mermaid has no object diagram; a classDiagram with instance names is the usual stand-in
classDiagram
  class c7_Customer {
    email = "a@b.io"
  }
  class o1_Order {
    id = "o-1"
    status = paid
  }
  class l1_OrderLine {
    lineNo = 1
    qty = 2
  }
  c7_Customer -- o1_Order
  o1_Order *-- l1_OrderLine

Package diagram Important ​

In plain words: folders and the "may import" arrows between them.

Common misunderstanding: "A package diagram is just the folder tree." The folder tree shows containment; the package diagram's value is the dependency arrows, which you can then enforce (Go's internal/, architecture tests, deptrac-style rules).

Definition: a package is a namespace for packageable elements, drawn as a tabbed folder. Dependencies between packages are dashed arrows, optionally with «import» (public import: the imported names become visible) or «access» (private import), and «merge» for package merge (used inside the UML metamodel itself, rarely in applications).

text
     Rule drawn on the package diagram         Enforced by
1    web ..> checkout                         Go: import path; PHP: architecture test
2    checkout ..> payments, inventory          only through interfaces (ports)
3    payments, inventory ..> platform          platform imports nothing above it
4    nobody ..> web                           a cycle here fails the Go build

Real scenario: the module map of a modular monolith; a layering rule ("domain imports nothing from infrastructure") that the Dependency Inversion chapter enforces; finding import cycles before Go refuses to compile them.

Use case diagramPackage diagramShopCustomerPSPPlace orderAuthenticateApply coupon«include»«extend»[coupon entered]webcheckoutpaymentsinventoryplatform«import»«use»«use»
text
@startuml
package web {}
package checkout {}
package payments {}
package inventory {}
package platform {}
web ..> checkout : <<import>>
checkout ..> payments : <<use>>
checkout ..> inventory : <<use>>
payments ..> platform
inventory ..> platform
@enduml
mermaid
flowchart TB
  web["pkg web"] -. import .-> checkout["pkg checkout"]
  checkout -. use .-> payments["pkg payments"]
  checkout -. use .-> inventory["pkg inventory"]
  payments -.-> platform["pkg platform"]
  inventory -.-> platform

Component diagram Must-know ​

In plain words: replaceable building blocks with sockets and plugs: what each part offers (provided interface) and what it needs (required interface).

Common misunderstanding: "A component is a microservice." In UML a component is any modular, replaceable unit: a Go package with an interface seam, a Laravel module, a library, or a service. Deployment is a separate question for the deployment diagram.

Definition: "A Component represents a modular part of a system that encapsulates its contents and whose manifestation is replaceable within its environment." Interfaces attach in two ways, from clause 10.4.4: a provided interface by "a circle or ball, often also called lollipop"; a required interface by "a half-circle or socket". A ball in a socket is an assembly connector. A port is a named interaction point on the component's border.

text
     Request                       Component       Required -> Provided
1    POST /orders                  Web API         PlaceOrder  -> Checkout
2    charge card                   Checkout        PaymentGateway -> PSP adapter
3    reserve stock                 Checkout        Inventory  -> Inventory adapter
4    persist                       Checkout        Orders     -> Order store

Real scenario: a hexagonal ("ports and adapters") service where the domain component requires PaymentGateway and two adapters provide it (Stripe in production, a fake in tests); a Laravel package whose service provider binds a contract to an implementation; a plug-in system (Microkernel).

«component»Web APInet/http · routes/api.php«component»Checkoutdomain + use casesPlaceOrder«component»PSP adapter«component»Inventory adapter«component»Order storePaymentGatewayInventoryOrdersBall (lollipop) = provided interface · socket = required interface · ball in socket = assembly connector
text
@startuml
component "Web API" as Web
component Checkout
component "PSP adapter" as PSP
component "Inventory adapter" as Inv
component "Order store" as Store
() PlaceOrder
() PaymentGateway
() "Inventory" as InvPort
() Orders
Checkout - PlaceOrder
Web ..> PlaceOrder : use
PSP - PaymentGateway
Inv - InvPort
Store - Orders
Checkout ..> PaymentGateway : use
Checkout ..> InvPort : use
Checkout ..> Orders : use
@enduml
mermaid
%% Mermaid has no UML component diagram; flowchart with circle nodes as interfaces
flowchart LR
  Web["«component» Web API"] -- requires --> PO(("PlaceOrder"))
  PO --- Checkout["«component» Checkout"]
  Checkout -- requires --> PG(("PaymentGateway"))
  PG --- PSP["«component» PSP adapter"]
  Checkout -- requires --> INV(("Inventory"))
  INV --- InvA["«component» Inventory adapter"]
  Checkout -- requires --> ORD(("Orders"))
  ORD --- Store["«component» Order store"]

Composite structure and profile diagrams Good to know ​

In plain words: a composite structure diagram opens one box and shows the parts and ports wired inside it; a profile diagram defines your own stereotypes.

Common misunderstanding: "Composite structure is the same as composition." Composition is a relationship on a class diagram; a composite structure diagram shows the runtime wiring of parts inside one classifier, connected through ports with connectors.

Definition: a composite structure diagram "Shows the internal structure of a StructuredClassifier" (Annex B, diagram kinds). A profile diagram shows stereotypes extending metaclasses: "A Stereotype defines an extension for one or more metaclasses". SysML, the systems-engineering language, is the best-known profile of UML.

DiagramWhen it pays offTypical reader
Composite structureEmbedded controllers, hardware/software parts, a component with internal sub-components and portsSystems engineers
ProfileDefining «aggregateRoot», «repository», «microservice» once so a tool can validate themTool builders, architecture teams

Deployment diagram Must-know ​

In plain words: the site plan: which machines and runtimes exist, which built files run on them, and which network paths connect them.

Common misunderstanding: "Deployment means Kubernetes YAML." The diagram is the picture of the topology; one diagram per environment (production, staging) is normal, because clustering and replicas differ.

Definition: "A Node is computational resource upon which Artifacts may be deployed, via Deployment relationships, for execution." Nodes are drawn as 3D boxes and can nest; standard kinds are «device» and «executionEnvironment». "An artifact is the specification of a physical piece of information that is used or produced by a software development process, or by deployment and operation of a system", for example "source files, scripts, and binary executable files, a table in a database system". An artifact «manifest»s a component. Lines between nodes are communication paths, labelled with the protocol.

text
     Hop                       From -> To                      Protocol    Failure to plan for
1    customer request          Browser -> Load balancer        HTTPS       TLS expiry
2    route                     Load balancer -> api pod        HTTP        pod restart
3    write order               api pod -> PostgreSQL primary   SQL/5432    failover, pool exhaustion
4    replicate                 primary -> replica              WAL stream  replica lag
5    event                     api pod -> RabbitMQ -> worker   AMQP        broker down, redelivery
6    charge                    api pod -> Stripe               HTTPS       timeout, idempotency key

Real scenario: an incident review that needs to show the replica a stale read came from; a capacity plan; a compliance document listing where card data can travel.

«device»Browser«node»Load balancer«executionEnvironment»k8s cluster«node»api pod«artifact»checkout-api (Go)«node»worker pod«artifact»laravel-worker:1.4«node»PostgreSQL«node»replica«node»RabbitMQ«external»StripeHTTPSHTTPSQLWALAMQPHTTPSNodes are 3D boxes; artifacts are what you ship (binaries, images); lines are communication paths.
text
@startuml
node "Browser" as B
node "Load balancer" as LB
node "k8s cluster" {
  node "api pod" {
    artifact "checkout-api (Go)" as api
  }
  node "worker pod" {
    artifact "laravel-worker:1.4" as worker
  }
}
database "PostgreSQL" as PG
database "replica" as REP
queue "RabbitMQ" as MQ
cloud "Stripe" as ST
B -- LB : HTTPS
LB -- api : HTTP
api -- PG : SQL
PG -- REP : WAL
api -- MQ : AMQP
worker -- MQ : AMQP
api -- ST : HTTPS
@enduml
mermaid
C4Deployment
  title Checkout, production
  Deployment_Node(k8s, "k8s cluster", "Kubernetes") {
    Deployment_Node(apiPod, "api pod") {
      Container(api, "checkout-api", "Go")
    }
    Deployment_Node(workerPod, "worker pod") {
      Container(worker, "laravel-worker", "PHP 8.4")
    }
  }
  Deployment_Node(db, "PostgreSQL primary") {
    ContainerDb(pg, "orders schema", "PostgreSQL")
  }
  Rel(api, pg, "SQL", "TCP 5432")

Use case diagram, and why it is weak Important ​

In plain words: stick figures (actors) connected to ovals (goals) inside a box (the system).

Common misunderstanding: "The use case diagram is the use case." The diagram only lists names. Jacobson's use cases are text: a main success scenario and extensions. Fowler's note on use cases and stories puts the value in the narrative: "Use cases organize requirements to form a narrative of how users relate to and use a system."

Definition: an actor is a role outside the subject; a use case is a goal the subject delivers. «include» is a dashed arrow "pointing from the base UseCase to the included UseCase"; «extend» is a dashed arrow "pointing from the extending UseCase towards the extended UseCase", optionally with a condition and extension points.

Why it is weak in practice:

ProblemWhat happensBetter tool
No order, no data, no errorsThe interesting part (what if the card is declined?) is invisibleUse case text, sequence diagram
«include»/«extend» debatesTeams argue arrows instead of requirementsPlain bullet extensions
Looks complete while saying littleTen ovals pass a review that found nothingUser stories with acceptance criteria
Functional decomposition creeps in"Validate address" becomes a use caseGoals at user level only

It still earns its place in a scope workshop: one diagram that shows actors (including secondary ones such as a payment provider) and the system boundary.

text
@startuml
left to right direction
actor Customer
actor "Payment provider" as PSP
rectangle Shop {
  usecase "Place order" as UC1
  usecase "Authenticate" as UC2
  usecase "Apply coupon" as UC3
}
Customer -- UC1
UC1 -- PSP
UC1 .> UC2 : <<include>>
UC3 .> UC1 : <<extend>>
@enduml
mermaid
%% Mermaid has no use case diagram; stadium nodes as ovals
flowchart LR
  Customer(["actor Customer"]) --- UC1(["Place order"])
  UC1 --- PSP(["actor Payment provider"])
  UC1 -. include .-> UC2(["Authenticate"])
  UC3(["Apply coupon"]) -. extend .-> UC1

Activity diagram Must-know ​

In plain words: a flowchart with superpowers: real parallelism (fork/join), swimlanes for who does each step, and data flowing between steps.

Common misunderstanding: "An activity diagram is an old flowchart." UML 2 activities have token semantics (Petri-net style): a join waits until every incoming flow has a token, which is exactly how a saga step that waits for two services behaves. A flowchart has no such rule.

Definition: actions (rounded rectangles) connected by control flows; an initial node (black dot) and an activity final node (bullseye); a flow final (circle with X) ends one flow only. "A ForkNode is a ControlNode that splits a flow into multiple concurrent flows"; a join synchronises them. "A DecisionNode is a ControlNode that chooses between outgoing flows", with guards in brackets; a merge node rejoins alternatives without waiting. "An ActivityPartition is a kind of ActivityGroup for identifying ActivityNodes that have some characteristics in common", drawn as swimlanes. Object nodes (rectangles such as o : Order [paid]) carry data along object flows.

text
     Token                     Node                 Rule
1    one token                 fork                 becomes two tokens: Reserve stock || Authorize payment
2    token A arrives           join                 waits
3    token B arrives           join                 both present -> one token continues to Create order
4    [invalid] at decision     decision             exactly one outgoing guard must be true
5    token reaches bullseye    activity final       the whole activity ends, all tokens destroyed

Real scenario: a checkout or onboarding workflow spanning teams; a data pipeline with parallel stages; a saga whose compensation paths need to be visible; a Laravel Bus::batch whose jobs run in parallel and a then callback that acts as the join.

CustomerCheckoutWarehousePaymentsSubmit cartValidate cart[invalid]Fix cart[valid]forkReserve stockAuthorize paymentjoinCreate ordero : Order[paid]Read confirmationSend confirmation
text
@startuml
|Customer|
start
repeat :Submit cart;
  |Checkout|
  :Validate cart;
backward:Fix cart;
repeat while (cart invalid?) is (yes)
->no;
fork
  |Warehouse|
  :Reserve stock;
fork again
  |Payments|
  :Authorize payment;
end fork
|Checkout|
:Create order;
note right: object flow o : Order [paid]
:Send confirmation;
|Customer|
:Read confirmation;
stop
@enduml
mermaid
flowchart TB
  subgraph Customer
    s((start)) --> submit[Submit cart]
    fix[Fix cart]
    readc[Read confirmation] --> e(((End)))
  end
  subgraph Checkout
    validate[Validate cart] --> valid{valid?}
    create[Create order] --> obj[/o : Order paid/]
    obj --> send[Send confirmation]
  end
  subgraph Warehouse
    reserve[Reserve stock]
  end
  subgraph Payments
    auth[Authorize payment]
  end
  submit --> validate
  valid -- no --> fix --> submit
  valid -- yes --> reserve & auth
  reserve & auth --> create
  send --> readc

State machine diagram Must-know ​

In plain words: the list of states one thing can be in, and the only arrows allowed between them. If there is no arrow, the change is illegal.

Common misunderstanding: "A status column with a dropdown is a state machine." Without the transition table, any code can set any status; the "shipped then pending again" bug is the result. The diagram's value is the arrows you did not draw.

Definition: states are rounded rectangles; a transition is labelled with the grammar from clause 14.2.4: [<trigger> [‘,’ <trigger>]* [‘[‘ <guard>’]’] [‘/’ <behavior-expression>]], that is event [guard] / effect. A state can have entry /, exit / and do / behaviours. A composite state contains regions; a state with several regions is orthogonal (isOrthogonal), and its regions run concurrently, drawn separated by a dashed line. Pseudostates include initial (dot), choice, junction, fork, join, entry/exit points, terminate, and history: "Deep history (deepHistory) represents the full state configuration of the most recent visit to the containing Region", while "Shallow history (shallowHistory) represents a return to only the topmost substate". Time events are written after(15 min), change events when(stock = 0).

text
     Event                    From        Guard                 To          Effect
1    stockReserved            Pending     [lines not empty]     Reserved    reserve()
2    paymentCaptured          Reserved    -                     Paid        -
3    paymentDeclined          Reserved    -                     Canceled    release()
4    after(15 min)            Pending     -                     Canceled    -
5    dispatched               Paid        -                     Fulfilment  enters both regions
6    hold, then resume        Fulfilment  -                     H* -> same substates as before
7    cancel                   Paid        -                     (no arrow)  rejected: illegal transition

Real scenario: order, payment, subscription and refund lifecycles; TCP connection states; document approval; any column named status. The Go and Laravel code below implement the top-level machine: Fulfilment is flattened into one Shipped state, and the 15-minute timer and the hold/resume history are left out. A test fails when the code and the top-level diagram drift.

Pendingentry / startTimer(15m)ReservedPaidstockReserved[lines not empty] / reserve()paymentCapturedCanceledcancelafter(15 min)paymentDeclined/ release()FulfilmentdispatchedH*PackingInTransitshippedInvoicingInvoicedcompletionOnHoldholdresume
text
@startuml
[*] --> Pending
Pending : entry / startTimer(15m)
Pending --> Reserved : stockReserved [lines not empty] / reserve()
Pending --> Canceled : cancel
Pending --> Canceled : after(15 min)
Reserved --> Paid : paymentCaptured
Reserved --> Canceled : paymentDeclined / release()
Paid --> Fulfilment : dispatched
state Fulfilment {
  [*] --> Packing
  Packing --> InTransit : shipped
  InTransit --> [*]
  --
  [*] --> Invoicing
  Invoicing --> Invoiced
  Invoiced --> [*]
}
Fulfilment --> OnHold : hold
OnHold --> Fulfilment[H*] : resume
Fulfilment --> [*]
Canceled --> [*]
@enduml
mermaid
stateDiagram-v2
  [*] --> Pending
  Pending: Pending (entry / startTimer)
  Pending --> Reserved: stockReserved [lines not empty] / reserve()
  Pending --> Canceled: cancel, after(15 min)
  Reserved --> Paid: paymentCaptured
  Reserved --> Canceled: paymentDeclined / release()
  Paid --> Fulfilment: dispatched
  state Fulfilment {
    [*] --> Packing
    Packing --> InTransit: shipped
    InTransit --> [*]
    --
    [*] --> Invoicing
    Invoicing --> Invoiced
    Invoiced --> [*]
  }
  Fulfilment --> OnHold: hold
  OnHold --> Fulfilment: resume (Mermaid has no history pseudostate)
  Fulfilment --> [*]
  Canceled --> [*]

Sequence diagram Must-know ​

In plain words: time runs down the page; each participant is a vertical dashed line; arrows are calls and replies in order. One diagram is one scenario.

Common misunderstanding: "A sequence diagram shows the algorithm." It shows one trace. Loops and branches are possible with combined fragments, but a diagram full of nested alts is code drawn badly; split it into one diagram per scenario.

Definition: "A Lifeline represents an individual participant in the Interaction." Execution specifications (activations) are "thin rectangles (gray or white) on the lifeline". Message kinds, from clause 17.4.4: "An asynchronous Message ... has an open arrow head", "A synchronous Message ... has a filled arrow head", "A reply Message ... has a dashed line", "An object creation Message ... has a dashed line with an open arrow head", and a deletion message ends in a destruction occurrence (an X). "A lost Message is a Message where the sending event occurrence is known, but there is no receiving event occurrence"; a found message is the reverse. A gate is a message end on the boundary of an interaction or fragment.

Combined fragments (interaction operators).

OperatorMeaning (UML 2.5.1, 17.6.3)Use it for
alt"At most one of the operands will be chosen"; [else] negates the othersSuccess vs failure branches
opt"either the (sole) operand happens or nothing happens"Optional step (send email if opted in)
loop"The loop operand will be repeated a number of times", loop(min,max)Retries, pagination
par"a parallel merge between the behaviors of the operands"Fan-out calls
breakOperand runs "instead of the remainder of the enclosing InteractionFragment"Early exit on error
criticalOperand is atomic: no interleavingA section under a lock
neg, assertInvalid trace; the only valid traceSpecifying forbidden behaviour
seq, strictWeak vs strict ordering of operandsRare; precision modelling
ignore, considerWhich messages are (ir)relevantRare
refAn InteractionUse: "a shorthand for copying the contents of the referenced Interaction"Reusing "Authenticate" in many diagrams
text
     Step  Lifeline -> lifeline              Arrow                   Code (Go)
1     1    Client -> CheckoutService         sync, filled head       svc.PlaceOrder(ctx, ...)
2     2    CheckoutService --> o:Order       «create», dashed open   checkout.NewOrder(id, customer)
3     3    CheckoutService -> Inventory      sync                    s.Inventory.Reserve(...)
4     4    alt [captured] / [declined]       combined fragment       if err := s.Payments.Charge(...); err != nil
5     5    CheckoutService ->> Broker        async, open head        s.Events.Publish(...) without waiting
6     6    CheckoutService --> Client        reply, dashed           return o, nil

Real scenario: an API flow in a pull request description; reproducing a race between a webhook and a redirect; showing which service owns a retry; documenting an OAuth or payment handshake; explaining a saga step and its compensation.

:Client:CheckoutService:Inventory:PaymentGateway:OrderRepo:Brokero:OrderplaceOrder(items)«create»reserve(lines)okalt[captured]charge(o, total)paymentIdfire(paymentCaptured)[declined]release(o)fire(paymentDeclined)save(o)opt[paid]OrderPaid201 / 402Filled head = synchronous call; dashed = reply or «create»; open head on solid line = asynchronous signal.
text
@startuml
participant Client
participant ":CheckoutService" as S
participant ":Inventory" as I
participant ":PaymentGateway" as P
participant ":OrderRepo" as R
queue ":Broker" as B
Client -> S ++ : placeOrder(items)
create Order
S --> Order : <<create>>
S -> I : reserve(lines)
I --> S : ok
alt captured
  S -> P : charge(o, total)
  P --> S : paymentId
  S -> Order : fire(paymentCaptured)
else declined
  S -> I : release(o)
  S -> Order : fire(paymentDeclined)
end
S -> R : save(o)
opt paid
  S ->> B : OrderPaid
end
return 201 / 402
@enduml
mermaid
sequenceDiagram
  participant C as Client
  participant S as CheckoutService
  participant I as Inventory
  participant P as PaymentGateway
  participant R as OrderRepo
  participant B as Broker
  C->>+S: placeOrder(items)
  create participant O as Order
  S-->>O: «create»
  S->>I: reserve(lines)
  I-->>S: ok
  alt captured
    S->>P: charge(o, total)
    P-->>S: paymentId
    S->>O: fire(paymentCaptured)
  else declined
    S->>I: release(o)
    S->>O: fire(paymentDeclined)
  end
  S->>R: save(o)
  opt paid
    S-)B: OrderPaid
  end
  S-->>-C: 201 / 402

Communication diagram Good to know ​

In plain words: the same messages as a sequence diagram, but drawn on the links between objects with numbers (1, 1.1, 1.2) instead of top-to-bottom order.

Common misunderstanding: "It is a different kind of information." It is the same interaction seen from the structure side: good for "who talks to whom", poor for "in which order". UML 1 called it a collaboration diagram.

Definition: lifelines as boxes connected by links; each message is a numbered label with a small arrow; nested numbers (1.1, 1.2) mean calls made while handling message 1. The left half of the object diagram figure shows the objects; the right half is the checkout as a communication diagram. Neither PlantUML nor Mermaid has a communication diagram type; an object diagram with numbered link labels is the usual approximation.

text
     Number   Link                           Message
1    1        Client - CheckoutService       placeOrder()
2    1.1      CheckoutService - Inventory    reserve()
3    1.2      CheckoutService - PSP          charge()
4    1.3      CheckoutService - OrderRepo    save()
5    1.4      CheckoutService - Broker       publish()
text
@startuml
' no communication diagram type: object diagram with numbered link labels
object ":Client" as C
object ":CheckoutService" as S
object ":Inventory" as I
object ":PaymentGateway" as P
object ":OrderRepo" as R
object ":Broker" as B
C -- S : 1: placeOrder() >
S -- I : 1.1: reserve() >
S -- P : 1.2: charge() >
S -- R : 1.3: save() >
S -- B : 1.4: publish() >
@enduml
mermaid
%% no communication diagram type: flowchart with numbered edge labels
flowchart LR
  C[":Client"] -- "1: placeOrder()" --> S[":CheckoutService"]
  S -- "1.1: reserve()" --> I[":Inventory"]
  S -- "1.2: charge()" --> P[":PaymentGateway"]
  S -- "1.3: save()" --> R[":OrderRepo"]
  S -- "1.4: publish()" --> B[":Broker"]

Interaction overview and timing diagrams Good to know ​

In plain words: an interaction overview is an activity diagram whose boxes are whole sequence diagrams (or refs to them); a timing diagram puts lifelines' states on a horizontal time axis.

Common misunderstanding: "Timing diagrams are for performance graphs." They show state over time with duration constraints ({t..t+3s}), the natural picture for timeouts, debouncing and hardware handshakes.

Definition: both are interaction diagrams (Annex A: "Interaction Overview Diagram - Interactions", "Timing Diagram - Interactions"). PlantUML supports timing diagrams (robust and concise participants); Mermaid has neither.

DiagramGood forExample
Interaction overviewChaining scenarios: login, then checkout, then (alt) 3-D Secureref Authenticate → decision → ref PlaceOrder
TimingTimeouts and state durationsOrder Pending for at most 15 minutes, then Canceled

Mechanics ​

Model, diagram and notation are three different things Important ​

Annex A opens with the distinction: "A UML model consists of elements such as packages, classes, and associations. The corresponding UML diagrams are graphical representations of parts of the UML model." The model lives in a tool's repository (or in your code); each diagram is a filtered view. That is why the same class can appear on ten diagrams with different compartments shown.

LayerWhat it isStandardWho cares
Abstract syntaxThe metamodel: Class, Property, Association, Lifeline…UML 2.5.1 (MOF-based)Tool builders
SemanticsWhat a composition or a join meansUML 2.5.1 semantics clausesEveryone who argues about arrows
NotationThe shapes and the text grammarsUML 2.5.1 notation clausesEveryone who draws
InterchangeSaving models and diagrams between toolsXMI files (UML.xmi), UML DI (Annex B)Tool migrations
ConstraintsPrecise rules over the modelOCL 2.4Model-driven teams

The text grammars you will actually type ​

text
property    [+|-|#|~] [/] name [: Type] [[m..n]] [= default] [{readOnly, ordered, unique, id, ...}]
operation   [+|-|#|~] name ( [in|out|inout] p : Type [= default], ... ) [: ReturnType] [{query, ...}]
transition  trigger [, trigger]* [ [guard] ] [ / effect ]
state       name  /  entry / action  /  do / activity  /  exit / action
message     [attribute =] name ( arguments ) [: return-value]
multiplicity 1 | 0..1 | * | 0..* | 1..* | m..n
frame       sd | stm | act | cmp | dep | pkg | uc  <name> [parameters]

Diagrams as code: where the text lives and how it renders Must-know ​

Text-based UML turns a picture into a reviewable diff. PlantUML describes itself as "Text in, diagram out" for use cases, and covers every UML diagram this page uses except communication, interaction overview and profile; Mermaid covers class, sequence and state natively and approximates the rest with flowcharts or its C4 diagrams. GitHub renders Mermaid:

"Diagram rendering is available in GitHub Issues, GitHub Discussions, pull requests, wikis, and Markdown files." — GitHub Docs, Creating diagrams

and "To create a Mermaid diagram, add Mermaid syntax inside a fenced code block with the mermaid language identifier."

PracticeHowWhy
Keep sources next to codedocs/diagrams/*.puml, *.mmd, or fenced blocks in README.mdThe diagram changes in the same PR as the code
Render in CIPlantUML or Mermaid CLI to SVG on mergeReviewers see the picture, the repo keeps the text
Generate what can be generatedClass/package diagrams from code (goplantuml, the umlgen tool below, the Laravel command below)Generated diagrams cannot rot
Hand-write what carries intentSequence, state, deploymentCode does not show intent, order or topology well
Test hand-written diagramsParse the text in a test and compare with codeDrift fails the build (Lab)
One question per diagramFilename says the question: checkout-declined.pumlFowler: selectivity

Reading a Go package into a class diagram ​

Go is the clearest example of the mismatch between UML's object model and a real language. The Go FAQ answers "Is Go an object-oriented language?" with "Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy." And on interfaces:

"A Go type implements an interface by implementing the methods of that interface, nothing more." — The Go FAQ, Why doesn't Go have "implements" declarations?

Go constructUML elementNote
type Order struct{...}ClassFields are attributes; methods with value or pointer receivers are operations
Exported / unexported identifier+ / ~Go visibility is per package, so ~ (package), not - (private)
type PaymentGateway interface{...}«interface»Usually declared by the consumer package
Type whose method set satisfies an interfaceRealization ..|>Implicit; nothing in the code names it. Assert with var _ I = (*T)(nil)
Struct embedding type B struct{ A }Composition plus promoted operationsNot generalization: B is not usable where A is expected
Field of value or slice type Lines []OrderLineComposition *-- with multiplicity 0..*Value semantics: the parts live inside the whole
Field of pointer or interface typeAssociation -->Shared or replaceable reference
Function parameter onlyDependency ..>
type Status string with constants«enumeration» (approximation)Go has no closed enums; the set is a convention
PackagePackage; internal/Import graph is the package diagram
Generic type Set[T comparable]Template class with parameter TUML templates are rarely drawn in practice

Two consequences. First, the realization arrow is a fact computed from method sets, so a generator must use go/types (types.Implements), not text search. Second, the interface usually lives next to its consumer, so the package diagram shows checkout owning PaymentGateway and stripe importing nothing from checkout except to satisfy it. That is Dependency Inversion drawn. Existing tools: GoPlantUML ("an open-source library and CLI that generates PlantUML class diagrams from Go source code") and the short umlgen program in this chapter's snippets.

Reading a Laravel module into a class diagram ​

PHP / Laravel constructUML elementNote
class Order extends ModelClass (stereotype «entity» if you like)Eloquent attributes are not declared fields: read the migration or $casts/casts()
public / protected / private+ / # / -PHP has no package visibility
hasMany(OrderLine::class)Association "1" -- "0..*"Composition only if the foreign key cascades (cascadeOnDelete())
belongsTo(Customer::class)Association "0..*" --> "1"Navigable from the child
hasOneAssociation "1" -- "0..1"
belongsToMany(...)->withPivot(...)Association classThe pivot (or custom pivot model) is the association class
morphTo / morphManyAssociation to an abstract type or «interface»Polymorphic association; draw the abstraction
implements PaymentGatewayRealization ..|>Explicit in PHP, unlike Go
extendsGeneralization --|>
use SomeTraitNo UML equivalentDraw as «trait» stereotype with a dependency, or flatten its members into the class
Backed enum OrderStatus: string«enumeration»Cases are literals; methods are operations
Service provider binding contract → implementationComponent assembly (ball and socket)The container is the wiring on the component diagram
Module folder / Composer packagePackagecomposer.json require is a package dependency

Go ​

Example: the checkout from the diagrams ​

order.go is the class diagram (Money, OrderLine, Order) and the state machine (a transition table plus a guard). The line number is the qualifier; Lines []OrderLine is the composition.

go
// Package checkout is the code behind the class and state machine
// diagrams of the UML chapter: every type here is one box on the
// class diagram, and Status/Fire are the state machine.
package checkout

import (
	"errors"
	"fmt"
)

// Money is a value object: two Money values with the same fields are equal.
// UML: «dataType» Money, no identity.
type Money struct {
	Cents    int64
	Currency string
}

// Add returns a new Money; Money is immutable.
func (m Money) Add(o Money) Money {
	return Money{Cents: m.Cents + o.Cents, Currency: m.Currency}
}

// Times multiplies the amount by a quantity.
func (m Money) Times(n int) Money {
	return Money{Cents: m.Cents * int64(n), Currency: m.Currency}
}

// OrderLine is a part of an Order (composition, filled diamond):
// it has no life outside its order and is deleted with it.
type OrderLine struct {
	LineNo    int // qualifier: Order[lineNo] -> 0..1 OrderLine
	SKU       string
	Qty       int
	UnitPrice Money
}

// Subtotal is a derived attribute (/subtotal in UML).
func (l OrderLine) Subtotal() Money { return l.UnitPrice.Times(l.Qty) }

// Status is the state of the Order state machine diagram.
type Status string

// The states, in the order they appear on the diagram.
const (
	Pending  Status = "pending"
	Reserved Status = "reserved"
	Paid     Status = "paid"
	Shipped  Status = "shipped"
	Canceled Status = "canceled"
)

// Event is a trigger on a transition.
type Event string

// Triggers of the Order state machine.
const (
	StockReserved Event = "stockReserved"
	PaymentOK     Event = "paymentCaptured"
	PaymentFailed Event = "paymentDeclined"
	Dispatch      Event = "dispatched"
	Cancel        Event = "cancel"
)

// transitions is the state machine as a table: source --trigger--> target.
// Anything missing from the table is an illegal transition.
var transitions = map[Status]map[Event]Status{
	Pending:  {StockReserved: Reserved, Cancel: Canceled},
	Reserved: {PaymentOK: Paid, PaymentFailed: Canceled},
	Paid:     {Dispatch: Shipped},
}

// ErrIllegalTransition is returned when a trigger has no transition
// from the current state.
var ErrIllegalTransition = errors.New("illegal transition")

// Order is the aggregate root. Lines are owned by composition;
// CustomerID is a plain association by identity, not by pointer.
type Order struct {
	ID         string
	CustomerID string
	Lines      []OrderLine
	Status     Status
}

// NewOrder is the «create» message on the sequence diagram.
func NewOrder(id, customerID string) *Order {
	return &Order{ID: id, CustomerID: customerID, Status: Pending}
}

// AddLine appends a line; the guard keeps lines immutable after reservation.
func (o *Order) AddLine(sku string, qty int, price Money) error {
	if o.Status != Pending {
		return fmt.Errorf("add line in state %s: %w", o.Status, ErrIllegalTransition)
	}
	o.Lines = append(o.Lines, OrderLine{LineNo: len(o.Lines) + 1, SKU: sku, Qty: qty, UnitPrice: price})
	return nil
}

// Total is the derived attribute /total : Money.
func (o *Order) Total() Money {
	total := Money{Currency: "EUR"}
	for _, l := range o.Lines {
		total = total.Add(l.Subtotal())
	}
	return total
}

// Fire applies a trigger. Guard: [lines not empty] on stockReserved.
func (o *Order) Fire(e Event) error {
	if e == StockReserved && len(o.Lines) == 0 {
		return fmt.Errorf("%s with no lines: %w", e, ErrIllegalTransition)
	}
	next, ok := transitions[o.Status][e]
	if !ok {
		return fmt.Errorf("%s --%s-->?: %w", o.Status, e, ErrIllegalTransition)
	}
	o.Status = next
	return nil
}

ports.go holds the required interfaces from the component diagram. Nothing in the package says which types provide them.

go
package checkout

import "context"

// The interfaces below are the provided/required interfaces of the
// component diagram (lollipop on the adapter, socket on the service).
// No Go type says "implements": satisfaction is implicit.

// PaymentGateway is required by Service and provided by a PSP adapter.
type PaymentGateway interface {
	Charge(ctx context.Context, orderID string, amount Money) (paymentID string, err error)
}

// Inventory is required by Service and provided by the inventory adapter.
type Inventory interface {
	Reserve(ctx context.Context, orderID string, lines []OrderLine) error
	Release(ctx context.Context, orderID string) error
}

// Orders is the repository port.
type Orders interface {
	Save(ctx context.Context, o *Order) error
}

// Publisher sends domain events (asynchronous messages on the sequence diagram).
type Publisher interface {
	Publish(ctx context.Context, topic string, payload any) error
}

service.go is the sequence diagram, one message per statement, including the alt fragment and the asynchronous publish.

go
package checkout

import (
	"context"
	"fmt"
)

// Service is the «control» lifeline of the checkout sequence diagram.
// It depends on four interfaces (dashed «use» arrows on the class diagram).
type Service struct {
	Orders    Orders
	Inventory Inventory
	Payments  PaymentGateway
	Events    Publisher
}

// Item is one requested line in a PlaceOrder command.
type Item struct {
	SKU   string
	Qty   int
	Price Money
}

// PlaceOrder follows the sequence diagram message by message.
func (s *Service) PlaceOrder(ctx context.Context, id, customerID string, items []Item) (*Order, error) {
	o := NewOrder(id, customerID) // create message
	for _, it := range items {
		if err := o.AddLine(it.SKU, it.Qty, it.Price); err != nil {
			return nil, err
		}
	}
	// 1: reserve stock (synchronous call, filled arrow head)
	if err := s.Inventory.Reserve(ctx, o.ID, o.Lines); err != nil {
		return nil, fmt.Errorf("reserve: %w", err)
	}
	if err := o.Fire(StockReserved); err != nil {
		return nil, err
	}
	// 2: charge; the alt fragment has two operands
	if _, err := s.Payments.Charge(ctx, o.ID, o.Total()); err != nil {
		// [declined]: compensate, then cancel
		_ = s.Inventory.Release(ctx, o.ID)
		_ = o.Fire(PaymentFailed)
		_ = s.Orders.Save(ctx, o)
		return o, fmt.Errorf("charge: %w", err)
	}
	// [captured]
	if err := o.Fire(PaymentOK); err != nil {
		return nil, err
	}
	if err := s.Orders.Save(ctx, o); err != nil {
		return nil, err
	}
	// 3: asynchronous message (open arrow head): fire and forget
	_ = s.Events.Publish(ctx, "order.paid", map[string]any{"id": o.ID, "total": o.Total().Cents})
	return o, nil
}

memory.go is an adapter that satisfies Orders implicitly; the compile-time assertion is the only written trace of the realization arrow.

go
package checkout

import (
	"context"
	"sync"
)

// MemoryOrders is an in-memory adapter. It never says "implements Orders",
// yet umlgen draws `Orders <|.. MemoryOrders`, because its method set
// satisfies the interface. The compile-time assertion below is the only
// place the relationship is written down.
type MemoryOrders struct {
	mu   sync.Mutex
	byID map[string]Order
}

var _ Orders = (*MemoryOrders)(nil)

// Save stores a copy of the order.
func (m *MemoryOrders) Save(_ context.Context, o *Order) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.byID == nil {
		m.byID = make(map[string]Order)
	}
	m.byID[o.ID] = *o
	return nil
}

The Go angle ​

Generate structure, hand-write behaviour. The class and package views of a Go module can be produced from source: go list -deps and go list -f with an imports template give the package diagram; go/types gives fields, method sets and interface satisfaction. The generator in this chapter prints PlantUML:

go
// Command umlgen reads one Go package and prints a PlantUML class diagram.
// It makes the Go/UML mismatch explicit. Exported identifiers become +
// (public) and unexported ones ~ (package), because Go visibility is per
// package, not per type. Interface satisfaction is implicit, so
// realizations are computed with types.Implements instead of being read
// from an "implements" keyword. A value or slice field of a local type
// becomes composition (*--); an interface or pointer field becomes an
// association (-->).
//
// Usage:
//
//	go run ./cmd/umlgen ./checkout > checkout.puml
package main

import (
	"fmt"
	"go/ast"
	"go/importer"
	"go/parser"
	"go/token"
	"go/types"
	"os"
	"path/filepath"
	"sort"
	"strings"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "usage: umlgen <package-dir>")
		os.Exit(2)
	}
	pkg, err := load(os.Args[1])
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Print(render(pkg))
}

func load(dir string) (*types.Package, error) {
	fset := token.NewFileSet()
	paths, err := filepath.Glob(filepath.Join(dir, "*.go"))
	if err != nil {
		return nil, err
	}
	var files []*ast.File
	for _, p := range paths {
		if strings.HasSuffix(p, "_test.go") {
			continue
		}
		f, err := parser.ParseFile(fset, p, nil, 0)
		if err != nil {
			return nil, err
		}
		files = append(files, f)
	}
	if len(files) == 0 {
		return nil, fmt.Errorf("no Go files in %s", dir)
	}
	conf := types.Config{Importer: importer.ForCompiler(fset, "source", nil)}
	return conf.Check(files[0].Name.Name, fset, files, nil)
}

func vis(name string) string {
	if token.IsExported(name) {
		return "+"
	}
	return "~"
}

func short(t types.Type, pkg *types.Package) string {
	return types.TypeString(t, types.RelativeTo(pkg))
}

func render(pkg *types.Package) string {
	var b, rel strings.Builder
	scope := pkg.Scope()
	names := scope.Names()
	sort.Strings(names)
	var ifaces []*types.Named
	for _, n := range names {
		if tn, ok := scope.Lookup(n).(*types.TypeName); ok {
			if named, ok := tn.Type().(*types.Named); ok && types.IsInterface(named) {
				ifaces = append(ifaces, named)
			}
		}
	}
	fmt.Fprintf(&b, "@startuml\npackage %s {\n", pkg.Name())
	for _, n := range names {
		tn, ok := scope.Lookup(n).(*types.TypeName)
		if !ok {
			continue
		}
		named, ok := tn.Type().(*types.Named)
		if !ok {
			continue
		}
		switch u := named.Underlying().(type) {
		case *types.Interface:
			fmt.Fprintf(&b, "  interface %s {\n", n)
			for i := 0; i < u.NumMethods(); i++ {
				m := u.Method(i)
				fmt.Fprintf(&b, "    %s%s%s\n", vis(m.Name()), m.Name(), strings.TrimPrefix(short(m.Type(), pkg), "func"))
			}
			b.WriteString("  }\n")
			continue
		case *types.Struct:
			fmt.Fprintf(&b, "  class %s {\n", n)
			for i := 0; i < u.NumFields(); i++ {
				f := u.Field(i)
				fmt.Fprintf(&b, "    %s%s : %s\n", vis(f.Name()), f.Name(), short(f.Type(), pkg))
				relate(&rel, n, f.Type(), pkg)
			}
		default:
			fmt.Fprintf(&b, "  class %s <<%s>> {\n", n, short(u, pkg))
		}
		ms := types.NewMethodSet(types.NewPointer(named))
		for i := 0; i < ms.Len(); i++ {
			m := ms.At(i).Obj()
			fmt.Fprintf(&b, "    %s%s%s\n", vis(m.Name()), m.Name(), strings.TrimPrefix(short(m.Type(), pkg), "func"))
		}
		b.WriteString("  }\n")
		for _, it := range ifaces {
			iface := it.Underlying().(*types.Interface)
			if iface.NumMethods() > 0 && types.Implements(types.NewPointer(named), iface) {
				fmt.Fprintf(&rel, "%s <|.. %s\n", it.Obj().Name(), n)
			}
		}
	}
	b.WriteString("}\n")
	b.WriteString(rel.String())
	b.WriteString("@enduml\n")
	return b.String()
}

// relate turns a field type into a UML relationship line.
func relate(w *strings.Builder, owner string, t types.Type, pkg *types.Package) {
	mult := "1"
	if s, ok := t.(*types.Slice); ok {
		t, mult = s.Elem(), "0..*"
	}
	ptr := false
	if p, ok := t.(*types.Pointer); ok {
		t, ptr = p.Elem(), true
	}
	named, ok := t.(*types.Named)
	if !ok || named.Obj().Pkg() != pkg {
		return
	}
	target := named.Obj().Name()
	switch {
	case types.IsInterface(named) || ptr:
		fmt.Fprintf(w, "%s --> \"%s\" %s\n", owner, mult, target)
	default:
		fmt.Fprintf(w, "%s *-- \"%s\" %s\n", owner, mult, target)
	}
}

Run on the checkout package it prints Orders <|.. MemoryOrders, Order *-- "0..*" OrderLine and Service --> "1" PaymentGateway: the arrows of the hand-drawn diagram, derived from code. Behaviour cannot be derived the same way, so the state machine is protected by a test that parses its PlantUML source and compares it with the transition table:

go
package checkout

import (
	"regexp"
	"strings"
	"testing"
)

// stateDiagram is the PlantUML source of the Order state machine (top level
// only). The test fails when code and diagram drift apart, in either direction.
const stateDiagram = `
@startuml
[*] --> Pending
Pending --> Reserved : stockReserved
Pending --> Canceled : cancel
Reserved --> Paid : paymentCaptured
Reserved --> Canceled : paymentDeclined
Paid --> Shipped : dispatched
Shipped --> [*]
Canceled --> [*]
@enduml
`

var edge = regexp.MustCompile(`^(\w+) --> (\w+) : (\w+)$`)

func TestCodeMatchesStateDiagram(t *testing.T) {
	drawn := map[string]bool{}
	for _, line := range strings.Split(stateDiagram, "\n") {
		if m := edge.FindStringSubmatch(strings.TrimSpace(line)); m != nil {
			drawn[strings.ToLower(m[1])+"-"+m[3]+"-"+strings.ToLower(m[2])] = true
		}
	}
	coded := map[string]bool{}
	for from, out := range transitions {
		for ev, to := range out {
			coded[string(from)+"-"+string(ev)+"-"+string(to)] = true
		}
	}
	for k := range drawn {
		if !coded[k] {
			t.Errorf("drawn but not coded: %s", k)
		}
	}
	for k := range coded {
		if !drawn[k] {
			t.Errorf("coded but not drawn: %s", k)
		}
	}
}

func TestGuardBlocksEmptyOrder(t *testing.T) {
	o := NewOrder("o-1", "c-1")
	if err := o.Fire(StockReserved); err == nil {
		t.Fatal("guard [lines not empty] did not hold")
	}
}

The demo command prints its own execution as PlantUML sequence lines, so you can render what the code actually did and compare it with the designed diagram:

go
// Command demo runs PlaceOrder against in-memory adapters and prints every
// message as a PlantUML sequence line, so the trace IS a sequence diagram.
//
//	go run ./cmd/demo            # happy path
//	go run ./cmd/demo -decline   # alt [declined] operand
package main

import (
	"context"
	"errors"
	"flag"
	"fmt"

	"academy/uml-diagrams/checkout"
)

type trace struct{}

func (trace) msg(from, to, arrow, text string) { fmt.Printf("%s %s %s : %s\n", from, arrow, to, text) }

type inventory struct{ t trace }

func (i inventory) Reserve(_ context.Context, id string, lines []checkout.OrderLine) error {
	i.t.msg("Service", "Inventory", "->", fmt.Sprintf("reserve(%s, %d lines)", id, len(lines)))
	i.t.msg("Inventory", "Service", "-->", "ok")
	return nil
}

func (i inventory) Release(_ context.Context, id string) error {
	i.t.msg("Service", "Inventory", "->", "release("+id+")")
	return nil
}

type payments struct {
	t       trace
	decline bool
}

func (p payments) Charge(_ context.Context, id string, m checkout.Money) (string, error) {
	p.t.msg("Service", "PSP", "->", fmt.Sprintf("charge(%s, %d %s)", id, m.Cents, m.Currency))
	if p.decline {
		p.t.msg("PSP", "Service", "-->", "declined")
		return "", errors.New("card declined")
	}
	p.t.msg("PSP", "Service", "-->", "pay_123")
	return "pay_123", nil
}

type orders struct{ t trace }

func (r orders) Save(_ context.Context, o *checkout.Order) error {
	r.t.msg("Service", "OrderRepo", "->", "save(status="+string(o.Status)+")")
	return nil
}

type bus struct{ t trace }

func (b bus) Publish(_ context.Context, topic string, _ any) error {
	b.t.msg("Service", "Broker", "->>", "publish "+topic)
	return nil
}

func main() {
	decline := flag.Bool("decline", false, "make the PSP decline the card")
	flag.Parse()
	t := trace{}
	svc := &checkout.Service{Orders: orders{t}, Inventory: inventory{t}, Payments: payments{t, *decline}, Events: bus{t}}
	fmt.Println("@startuml")
	t.msg("Client", "Service", "->", "placeOrder(o-1)")
	o, err := svc.PlaceOrder(context.Background(), "o-1", "c-7", []checkout.Item{
		{SKU: "BOOK-1", Qty: 2, Price: checkout.Money{Cents: 1500, Currency: "EUR"}},
		{SKU: "PEN-9", Qty: 1, Price: checkout.Money{Cents: 300, Currency: "EUR"}},
	})
	if err != nil {
		t.msg("Service", "Client", "-->", "error: "+err.Error())
	} else {
		t.msg("Service", "Client", "-->", "201 "+string(o.Status))
	}
	fmt.Println("@enduml")
}

Laravel ​

Example: the same checkout ​

The state machine as a backed enum; each case is a state and allowedTransitions() lists the outgoing arrows.

php
<?php

namespace App\Enums;

/**
 * The Order state machine diagram as a backed enum.
 * Each case is a state; allowedTransitions() is the set of outgoing arrows.
 */
enum OrderStatus: string
{
    case Pending = 'pending';
    case Reserved = 'reserved';
    case Paid = 'paid';
    case Shipped = 'shipped';
    case Canceled = 'canceled';

    /** @return list<self> */
    public function allowedTransitions(): array
    {
        return match ($this) {
            self::Pending => [self::Reserved, self::Canceled],
            self::Reserved => [self::Paid, self::Canceled],
            self::Paid => [self::Shipped],
            self::Shipped, self::Canceled => [], // final states
        };
    }

    public function canTransitionTo(self $next): bool
    {
        return in_array($next, $this->allowedTransitions(), true);
    }
}

The Eloquent model: hasMany and belongsTo are the associations, the casts() entry links the attribute to the enumeration, and transitionTo() refuses any arrow that is not on the diagram.

php
<?php

namespace App\Models;

use App\Enums\OrderStatus;
use DomainException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * Class diagram: Order "1" *-- "1..*" OrderLine, Order "0..*" --> "1" Customer.
 * The composition is enforced by the foreign key ON DELETE CASCADE,
 * not by Eloquent: hasMany() alone is only an association with multiplicity.
 */
class Order extends Model
{
    protected $fillable = ['customer_id', 'status'];

    protected function casts(): array
    {
        return ['status' => OrderStatus::class];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class);
    }

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class);
    }

    /** Derived attribute /total in cents. */
    public function total(): int
    {
        return (int) $this->lines->sum(fn (OrderLine $l) => $l->qty * $l->unit_price_cents);
    }

    /** One transition of the state machine; illegal arrows throw. */
    public function transitionTo(OrderStatus $next): void
    {
        if (! $this->status->canTransitionTo($next)) {
            throw new DomainException("Illegal transition {$this->status->value} -> {$next->value}");
        }
        $this->status = $next;
        $this->save();
    }
}

The sequence diagram as an Action. The interfaces at the top are the sockets of the component diagram; a service provider binds them to adapters.

php
<?php

namespace App\Checkout;

use App\Enums\OrderStatus;
use App\Events\OrderPaid;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

/** Required interfaces (sockets on the component diagram). */
interface PaymentGateway
{
    /** @throws PaymentDeclined */
    public function charge(int $orderId, int $amountCents): string;
}

interface Inventory
{
    /** @param array<int, array{sku: string, qty: int}> $lines */
    public function reserve(int $orderId, array $lines): void;

    public function release(int $orderId): void;
}

final class PaymentDeclined extends \RuntimeException {}

/**
 * The checkout sequence diagram as an Action: one method per lifeline message.
 */
final class PlaceOrder
{
    public function __construct(
        private readonly Inventory $inventory,
        private readonly PaymentGateway $payments,
    ) {}

    /** @param array<int, array{sku: string, qty: int, unit_price_cents: int}> $items */
    public function handle(int $customerId, array $items): Order
    {
        // «create» message: the order and its lines appear in one transaction
        $order = DB::transaction(function () use ($customerId, $items) {
            $order = Order::create(['customer_id' => $customerId, 'status' => OrderStatus::Pending]);
            $order->lines()->createMany($items);

            return $order;
        });

        // 1: synchronous call
        $this->inventory->reserve($order->id, $order->lines->map->only('sku', 'qty')->all());
        $order->transitionTo(OrderStatus::Reserved);

        // 2: alt [captured] / [declined]
        try {
            $this->payments->charge($order->id, $order->total());
        } catch (PaymentDeclined $e) {
            $this->inventory->release($order->id); // compensation
            $order->transitionTo(OrderStatus::Canceled);
            throw $e;
        }
        $order->transitionTo(OrderStatus::Paid);

        // 3: asynchronous message (open arrow head); listeners may be queued
        OrderPaid::dispatch($order);

        return $order;
    }
}

The Laravel angle ​

Eloquent relationships declare return types (HasMany, BelongsTo, BelongsToMany), which makes reverse engineering cheap: reflection finds relationship methods without running a query, and getRelated() names the other class. This Artisan command prints a Mermaid class diagram you can paste into a pull request:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Relation;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;

/**
 * php artisan uml:models > docs/models.mmd
 *
 * Reads app/Models, finds relationship methods by their declared return
 * type, and prints a Mermaid classDiagram. Relationships become plain
 * associations with multiplicities: Eloquent cannot tell aggregation from
 * composition; only the foreign key's ON DELETE rule can.
 */
final class UmlModels extends Command
{
    protected $signature = 'uml:models';

    protected $description = 'Print a Mermaid class diagram of the Eloquent models';

    /** Relation class => [multiplicity at this end, multiplicity at the other end] */
    private const MULTIPLICITY = [
        HasMany::class => ['"1"', '"0..*"'],
        HasOne::class => ['"1"', '"0..1"'],
        BelongsTo::class => ['"0..*"', '"1"'],
        BelongsToMany::class => ['"0..*"', '"0..*"'],
    ];

    public function handle(): int
    {
        $this->line('classDiagram');
        foreach (glob(app_path('Models/*.php')) as $file) {
            $class = 'App\\Models\\'.basename($file, '.php');
            $ref = new ReflectionClass($class);
            if (! $ref->isSubclassOf(Model::class) || $ref->isAbstract()) {
                continue;
            }
            $this->line('  class '.$ref->getShortName());
            foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
                $this->relationLine($ref, $method);
            }
        }

        return self::SUCCESS;
    }

    private function relationLine(ReflectionClass $ref, ReflectionMethod $method): void
    {
        $type = $method->getReturnType();
        if ($method->class !== $ref->getName()
            || $method->getNumberOfRequiredParameters() > 0
            || ! $type instanceof ReflectionNamedType
            || ! is_subclass_of($type->getName(), Relation::class)) {
            return;
        }
        $kind = $type->getName();
        [$here, $there] = self::MULTIPLICITY[$kind] ?? ['', ''];
        // Building a relation object does not run a query; it only needs the related model.
        $related = $ref->newInstance()->{$method->getName()}()->getRelated();
        $arrow = $kind === BelongsTo::class ? '-->' : '--';
        $this->line(sprintf(
            '  %s %s %s %s %s : %s',
            $ref->getShortName(), $here, $arrow, $there, class_basename($related), $method->getName(),
        ));
    }
}

What it cannot see is just as instructive: aggregation versus composition lives in the migration (foreignId('order_id')->constrained()->cascadeOnDelete()), not in the model; association classes are pivots declared with withPivot('active', 'created_by') or ->using(CustomPivot::class); traits have no UML element. Draw those by hand, and keep the generated part generated.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Diagrams rot after one sprintGenerate structure, test behaviourumlgen, uml:models, the state-machine drift testWrong diagrams fail CIOnly works for what code can express
Diagram shows everything, says nothingOne question per diagramHide members, show 5–9 boxes, name the file after the questionReadable in a reviewMore, smaller files
Arguments about arrowsAgree on the six lines and three rulesComposition = lifecycle; dependency = temporary; aggregation = avoidShorter reviewsSome precision lost on purpose
Wrong diagram for the questionUse the choosing tableOrdering question → sequence; legality question → stateAnswers the real questionNeeds a little UML literacy
Go code "has no classes"Map types, method sets and packagesGo mapping tableHonest diagrams of GoRealization arrows must be computed
Architecture diagrams mix levelsC4 zoom levels for structure, UML for behaviourUML and C4Each picture has one audienceTwo notations to know
Images in the repo nobody can editText sources, rendered on demandPlantUML/Mermaid in MarkdownDiffable, reviewableAuto-layout is sometimes ugly

The worked system: checkout end to end ​

One system, six views, all describing the same code. Read them in this order when you join the team.

ViewQuestionFigureCode
ClassWhat is an order made of?Belowcheckout/order.go, Order.php
SequenceWhat happens on "Place order"?Sequenceservice.go, PlaceOrder.php
State machineWhich status changes are legal?State machinetransitions map, OrderStatus enum
ActivityWho does what, what runs in parallel?ActivityWorkflow / saga orchestration
ComponentWhich parts plug into which interfaces?Componentports.go, service provider bindings
DeploymentWhat runs where?DeploymentContainer images, k8s manifests
Customer- id : CustomerId- email : String«entity»Order- id : OrderId- status : OrderStatus+ /total : Money+ addLine(sku, qty, price)+ fire(e : Event)lineNoOrderLine- sku : String- qty : Integer {qty > 0}- unitPrice : Money+ /subtotal() : Money0..1linesProduct- sku : String- price : Money0..*1«enumeration»OrderStatusPendingReservedPaidShippedCanceledstatus10..*Payment- amount : Money{abstract}10..*CardPayment- last4 : StringWalletPayment- provider : String«control»CheckoutService+ placeOrder(cmd)«interface»PaymentGateway+ charge(o, amt)StripeGateway- apiKey : Secret«create»«use»Filled diamond = composition, qualified by lineNo; the service depends only on the interface.

The class diagram also decides the schema. Each notation choice becomes a concrete database rule:

sql
-- Composition (filled diamond): lines die with their order.
-- Qualified association Order[lineNo] -> 0..1 OrderLine: composite unique key.
-- {qty > 0}: a CHECK constraint. «enumeration» OrderStatus: a CHECK list.
CREATE TABLE orders (
  id          BIGSERIAL PRIMARY KEY,
  customer_id BIGINT NOT NULL REFERENCES customers(id),          -- association 0..* -> 1
  status      TEXT   NOT NULL DEFAULT 'pending'
              CHECK (status IN ('pending','reserved','paid','shipped','canceled'))
);
CREATE TABLE order_lines (
  order_id          BIGINT  NOT NULL REFERENCES orders(id) ON DELETE CASCADE,  -- composition
  line_no           INT     NOT NULL,                                          -- qualifier
  sku               TEXT    NOT NULL REFERENCES products(sku),                 -- association -> 1 Product
  qty               INT     NOT NULL CHECK (qty > 0),                          -- constraint {qty > 0}
  unit_price_cents  BIGINT  NOT NULL,
  PRIMARY KEY (order_id, line_no)
);
-- Association class (Student, Course) -> Enrollment: a join table with its own columns.
CREATE TABLE enrollments (
  student_id BIGINT NOT NULL REFERENCES students(id),
  course_id  BIGINT NOT NULL REFERENCES courses(id),
  grade      TEXT,
  enrolled_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (student_id, course_id)
);
-- Generalization Payment <|-- CardPayment, WalletPayment: single table with a type column
-- (or one table per subclass; UML does not decide this, your queries do).
CREATE TABLE payments (
  id       BIGSERIAL PRIMARY KEY,
  order_id BIGINT NOT NULL REFERENCES orders(id),
  kind     TEXT   NOT NULL CHECK (kind IN ('card','wallet')),
  amount_cents BIGINT NOT NULL,
  last4    TEXT,
  provider TEXT
);

This maps the same way on PostgreSQL, MySQL with InnoDB (the MySQL manual: "As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines"), SQL Server and Oracle; SQLite enforces foreign keys only after PRAGMA foreign_keys = ON. Document stores such as MongoDB express composition by embedding the lines in the order document, and association by storing an id.

UML and the C4 model ​

The C4 model is "an easy to learn, developer friendly approach to software architecture diagramming" built on "A set of hierarchical abstractions - software systems, containers, components, and code." Its creator, Simon Brown, is direct about scope: "you don’t need to use all 4 levels of diagram; only those that add value - the system context and container diagrams are sufficient for most software development teams."

1 · System ContextShopPSPclosest UML:Use case / noneCustomer → Shop → Stripe2 · ContainersSPAAPIWorkerDBMQclosest UML:Deployment + componentSPA · API · worker · DB · MQ3 · ComponentsAPI containerCheckoutPSP adapterOrder storeclosest UML:ComponentCheckout · PSP adapter · Store4 · CodeOrder- status+ fire()OrderLine- qtyclosest UML:ClassOrder ◆— OrderLineZoom in left to right. Simon Brown: context and container diagrams are enough for most teams.
C4 levelShowsAudience (C4 site)Closest UMLPrefer which?
System contextPeople and systems around yours"Everybody, both technical and non-technical people"Use case (actors + boundary)C4
ContainerApplications and data stores, technologies, protocolsArchitects, developers, operationsComponent + deploymentC4
ComponentComponents inside one containerArchitects, developersComponentEither; generate if long-lived
CodeClasses inside one componentDevelopersClassUML class diagram, generated by an IDE
Supporting: dynamicNumbered interactionsDevelopersCommunication / sequenceUML sequence
Supporting: deploymentMapping containers to infrastructureOperationsDeploymentEither
(none)States of one entityDevelopers, productState machineUML (C4 has nothing)

"Unfortunately, UML usage seems to be in decline, and many teams have reverted to using ad hoc boxes and lines diagrams once again." — C4 model FAQ, c4model.com

The practical split: C4 for the static architecture map, UML for behaviour and for code-level structure. C4's own FAQ recommends supplementing with UML state and timing diagrams, and says that to document "a library, framework or SDK, you might be better off using something like UML." Mermaid supports C4 (C4Context, C4Container, C4Component, C4Dynamic, C4Deployment), and "Mermaid's C4 diagram syntax is compatible with plantUML."

mermaid
C4Context
  title Shop, system context
  Person(customer, "Customer", "Buys products")
  System(shop, "Shop", "Catalogue, checkout, orders")
  System_Ext(stripe, "Stripe", "Card payments")
  System_Ext(mail, "E-mail provider")
  Rel(customer, shop, "Places orders", "HTTPS")
  Rel(shop, stripe, "Charges cards", "HTTPS")
  Rel(shop, mail, "Sends confirmations", "SMTP")

Choosing the diagram ​

Situation / questionRecommendationExtra techniqueReason
"Who calls whom, in what order?"SequenceOne diagram per scenario; alt for the failure pathOrder is the vertical axis
"Is this status change allowed?"State machineDrift test against the code's transition tableThe missing arrows are the rules
"What is this domain made of?"Class (5–9 boxes)Object diagram for one tricky exampleMultiplicity and lifecycle are explicit
"Which modules may import which?"PackageArchitecture tests; Go internal/Arrows become enforceable rules
"Where are the seams for testing/swapping?"Component with ball and socketFakes for every required interfaceShows ports and adapters
"What runs where?"Deployment, one per environmentLabel protocols and portsIncidents happen on the lines
"What is the whole system and who uses it?"C4 context + containerKeep it on one pageNon-technical readers
"Who does what across teams, with parallel steps?"Activity with swimlanesFork/join for parallel workConcurrency and ownership visible
"What are the user goals?"Use case text (+ one diagram)Stories with acceptance criteriaThe diagram alone says little
Timeouts and durationsTiming (PlantUML) or state machine with after()Time is the axis
Explaining a design in a PRMermaid fenced blockRenders on GitHubZero tooling for reviewers
Regulated blueprintFull UML tool, XMI exportModel reviewsCompleteness is the requirement

In architecture: from a single process to a distributed system ​

UML scales by changing which diagram carries the weight: inside one process the class and state diagrams matter most; across processes the sequence and deployment diagrams do.

Monolith: one process, one database ​

How it shows up: a class diagram of the domain, a state machine per lifecycle entity, a sequence diagram per important use case. Everything is a method call, so sequence diagrams are mostly synchronous arrows.

Simplest correct usage: keep docs/diagrams/ with three files per bounded area (<area>-class.puml, <area>-states.puml, <area>-<usecase>.puml) and generate the class diagram where possible.

Example (simple): a blog: Post *-- Comment, Post --> Author, state machine Draft → Published → Archived.

Example (complex): the checkout on this page in one Laravel app: PlaceOrder Action, OrderStatus enum, Eloquent models; the activity diagram's fork becomes Bus::batch([...])->then(...).

Modular monolith and multiple databases ​

How it shows up: the package diagram becomes the most important picture: one package per module, arrows only through published interfaces, and a component diagram for each module's provided and required interfaces. Each module owns its tables; the class diagram stops at the module boundary and refers to other modules' entities by id only (an association to an id type, not to the class).

text
     Module boundary rule                         UML expression
1    checkout may call payments                    checkout ..> payments «use» (package diagram)
2    only through PaymentGateway                   socket on Checkout, lollipop on Payments (component)
3    checkout stores customer_id, not Customer     attribute customerId : CustomerId, no association line
4    payments must not import checkout             no arrow; an architecture test fails if one appears

Microservices: sequence and deployment carry the weight ​

What survives: component diagrams (now each component is a service), state machines (each service's entities), class diagrams inside each service. What changes: sequence diagrams gain asynchronous arrows, par fragments and failure operands, because every arrow can now fail independently (Distribution of Components). Draw the network as part of the design, not as an implementation detail.

text
     Checkout saga (choreography) as a sequence
1    checkout-svc ->> broker : OrderPlaced          (async, open head; via outbox)
2    broker ->> inventory-svc : OrderPlaced
3    inventory-svc ->> broker : StockReserved
4    broker ->> payment-svc : StockReserved
5    alt [declined]  payment-svc ->> broker : PaymentFailed ; inventory-svc releases stock
6    every lifeline is a service; every arrow needs a timeout, retry rule and idempotency key

Example: the outbox makes arrow 1 reliable; the saga page draws the compensation path. A C4 container diagram replaces the old component diagram as the overview; UML sequence diagrams document each saga.

Distributed data: replicas, caches and regions ​

Where diagrams break: a sequence diagram with one :Database lifeline hides the primary/replica split, the cache in front, and the region boundary. Draw them as separate lifelines; that is where the bugs live.

text
     Read-your-writes bug, drawn honestly
1    Client -> api : POST /orders            -> api -> primary : INSERT (commit)
2    Client -> api : GET /orders/42          -> api -> replica : SELECT  (replica lag 300 ms)
3    replica --> api : not found             -> api --> Client : 404 for an order that exists
4    fix drawn: alt [read after own write within 1 s] api -> primary ; else api -> replica

A deployment diagram with regions, replicas and cache nodes, labelled with replication mode (synchronous or asynchronous) and failover direction, belongs in every incident runbook. The database side of this is on Replication & Failover; in Redis-backed caches, draw the cache as its own lifeline with the TTL on the arrow.

Scaling path: 1×, 10×, 100× ​

ScaleStructureDiagram practice
1× (one team, one app)MonolithClass + state + a few sequence diagrams, as Mermaid in Markdown
10× (several teams, one repo)Modular monolithPackage and component diagrams enforced by tests; generated class diagrams per module
100× (many teams, many services)Services, regionsC4 context/container per system, UML sequence per cross-service flow, deployment per environment, state machines per aggregate

Lab: generate, render and test diagrams ​

Everything runs offline with Go installed.

Setup.

bash
cd docs/snippets/design/uml-diagrams/go
go vet ./... && go test ./...
# ok  academy/uml-diagrams/checkout

Step 1: generate the class diagram from code.

bash
go run ./cmd/umlgen ./checkout > /tmp/checkout.puml
grep -E '<\|\.\.|\*--|-->' /tmp/checkout.puml
# Item *-- "1" Money
# Orders <|.. MemoryOrders
# Order *-- "0..*" OrderLine
# Order *-- "1" Status
# OrderLine *-- "1" Money
# Service --> "1" Orders
# Service --> "1" Inventory
# Service --> "1" PaymentGateway
# Service --> "1" Publisher

Compare with the hand-drawn checkout class diagram. Expected differences: the generator draws Status as composition (it is a value field) where the hand drawing shows an association to an enumeration, and it cannot know the qualifier. Note also ~mu and ~byID on MemoryOrders: unexported means package visibility.

Step 2: render it. Paste /tmp/checkout.puml into any PlantUML renderer (IDE plug-in or PlantUML server). As an exercise, add a -mermaid flag to umlgen that prints a classDiagram instead (the header, the package wrapper and the interface syntax all change), and paste its output into a GitHub comment.

Step 3: record the actual sequence.

bash
go run ./cmd/demo
# @startuml
# Client -> Service : placeOrder(o-1)
# Service -> Inventory : reserve(o-1, 2 lines)
# Inventory --> Service : ok
# Service -> PSP : charge(o-1, 3300 EUR)
# PSP --> Service : pay_123
# Service -> OrderRepo : save(status=paid)
# Service ->> Broker : publish order.paid
# Service --> Client : 201 paid
# @enduml
go run ./cmd/demo -decline
# ... PSP --> Service : declined
# Service -> Inventory : release(o-1)
# Service -> OrderRepo : save(status=canceled)
# Service --> Client : error: charge: card declined

The two runs are the two operands of the alt fragment. Render both and lay them next to the designed sequence diagram.

Step 4: make the diagram fail the build. In checkout/order.go add Paid: {Dispatch: Shipped, Cancel: Canceled} to the transition table and run go test ./checkout. Expected: coded but not drawn: paid-cancel-canceled. Either draw the arrow (and decide who refunds) or remove the code.

Step 5: break the guard. Remove the len(o.Lines) == 0 check from Fire. Expected: TestGuardBlocksEmptyOrder fails with "guard [lines not empty] did not hold".

Step 6 (Laravel, optional). Register UmlModels in a Laravel 13 app with Order, OrderLine and Customer models and run php artisan uml:models. Expected output starts with classDiagram and contains Order "1" -- "0..*" OrderLine : lines and Order "0..*" --> "1" Customer : customer; paste it into a PR description and GitHub renders it.

Common misconceptions ​

BeliefReality
UML is a processIt is a notation; processes (RUP, agile) are separate
A diagram must be completeA diagram is a view; omitted means "not shown", not "absent"
Hollow diamond = has-a, filled = strong has-aEvery association is has-a; only composition has defined lifecycle semantics
Arrows on associations mean data flowThey mean navigability (who can reach whom)
Go embedding is inheritanceIt is composition with promoted methods; no subtyping
Interfaces in Go are drawn like Java'sRealization is implicit and must be computed from method sets
Use case diagrams capture requirementsThe text scenarios do; the diagram is a table of contents
A sequence diagram documents the algorithmIt documents one trace; branch-heavy diagrams belong in code
A status column is a state machineOnly if illegal transitions are rejected somewhere
C4 replaced UMLC4 covers static architecture; behaviour still needs UML
Mermaid renders all UMLClass, sequence and state natively; others are approximations
Diagrams always rotGenerated diagrams and diagram tests do not
Communication and sequence diagrams carry different informationSame interaction, different layout

Cheat sheet ​

TopicRemember
Families7 structure, 7 behaviour (4 of them interaction)
Daily sevenClass, package, component, deployment, activity, state machine, sequence
Visibility+ public, - private, # protected, ~ package (Go unexported)
Multiplicity1, 0..1, *, 1..*; not shown ≠ one
Six linesAssociation, aggregation (hollow ◇), composition (filled ◆), dependency (dashed →), generalization (△), realization (dashed △)
CompositionPart in at most one whole; deleted with it → ON DELETE CASCADE
Association classLink with data → join table / pivot with columns
Sequence arrowsFilled = sync, open = async, dashed = reply/create, X = destroy
Fragmentsalt, opt, loop, par, break, critical, ref
Transition labelevent [guard] / effect
HistoryH shallow (top substate), H* deep (full configuration)
ComponentLollipop = provided, socket = required
ModesSketch (selective), blueprint (complete), programming language (generated)
C4Context and container for everyone; UML for behaviour and code
Diagrams as codeText in repo, render in CI, generate structure, test behaviour

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Name the two diagram families and two diagrams of each. Must-know ​

Answer

Answer: Structure (class, object, package, component, composite structure, deployment, profile) and behaviour (use case, activity, state machine, plus interaction diagrams: sequence, communication, interaction overview, timing). See The 14 diagrams.

2 — What exactly does a filled diamond promise that a hollow one does not? Important ​

Answer

Answer: A part belongs to at most one composite at a time, and when the composite is deleted its parts are deleted with it. Shared aggregation's semantics "varies by application area and modeler". See Class diagram.

3 — Which visibility symbol should a Go unexported field get, and why? Must-know ​

Answer

Answer: ~ (package), because Go hides identifiers per package, not per type; any code in the same package can use it. See Reading Go.

4 — How do you draw "Order line has quantity and price at time of sale, linking Order and Product" in UML and in SQL? Important ​

Answer

Answer: An association class OrderLine attached by a dashed line to the Order–Product association; in SQL a join table with its own columns (in Laravel a pivot with withPivot or a custom pivot model). See association class and the schema.

5 — In a sequence diagram, how do you tell a synchronous call from an asynchronous one? Must-know ​

Answer

Answer: Synchronous: solid line with a filled arrowhead (and usually a reply). Asynchronous: solid line with an open arrowhead. Replies are dashed. See Sequence diagram.

6 — What is the difference between alt and opt? Must-know ​

Answer

Answer: alt chooses at most one of several guarded operands; opt has one operand that either happens or not, equivalent to an alt with an empty second operand.

7 — Read this transition label: paymentDeclined [attempts < 3] / scheduleRetry(). Important ​

Answer

Answer: Trigger paymentDeclined, guard attempts < 3, effect scheduleRetry(): when the event arrives and the guard is true, the effect runs and the state changes. See State machine.

8 — A composite state is left via hold and re-entered via H*. What state is the machine in after resume? Good to know ​

Answer

Answer: Deep history restores the full configuration of the last visit: in every orthogonal region, the same nested substate as before hold (e.g. InTransit and Invoiced). Shallow history H would restore only the top-level substates and enter them by their defaults.

9 — Why is the use case diagram considered weak, and what do you use instead? Important ​

Answer

Answer: It shows names of goals but no order, data or failure paths. Use the use case text (main scenario and extensions), user stories with acceptance criteria, and sequence diagrams for the flows. See Use case.

10 — When would you choose a C4 container diagram over a UML deployment diagram, and when the other way round? Important ​

Answer

Answer: C4 container for the system overview (applications, data stores, technologies) for a broad audience; UML/C4 deployment for one environment's nodes, replicas and network paths, for operations and incident work. See UML and C4.

11 — How can a hand-written state diagram be kept from rotting? Important ​

Answer

Answer: Keep it as text in the repository and add a test that parses the diagram's transitions and compares them with the code's transition table in both directions. See the Lab, step 4.

Glossary ​

TermMeaning
UMLUnified Modeling Language, OMG standard; current version 2.5.1 (formal/2017-12-05)
OMGObject Management Group, the standards body that owns UML, OCL, XMI, SysML
Booch, OMT, OOSEThe three methods UML unified (Booch; Rumbaugh's Object Modeling Technique; Jacobson's Object-Oriented Software Engineering)
Model vs diagramThe model holds elements; a diagram is one graphical view of part of it
Structure diagramShows elements "irrespective of time": class, object, package, component, composite structure, deployment, profile
Behavior diagramShows dynamic behaviour: use case, activity, state machine, interaction diagrams
Interaction diagramSequence, communication, interaction overview, timing
Frame / headingOptional border with sd, stm, act, cmp, dep, pkg, uc + name
ClassifierAbstract metaclass for things with features: class, interface, component, use case…
Visibility+ public, - private, # protected, ~ package
MultiplicityAllowed number of values or linked objects, lower..upper
Derived (/)Computed from other values, e.g. /total
AssociationStructural relationship between classifiers; ends have multiplicity and navigability
NavigabilityOpen arrowhead on an association end: you can reach that end efficiently
Aggregation (shared)Hollow diamond; whole–part with unspecified semantics
Composition (composite)Filled diamond; part in at most one whole, deleted with it
DependencyDashed arrow; client uses supplier; keywords «use», «create», «import»
GeneralizationHollow triangle; subtype relationship
Realization / interface realizationDashed line with hollow triangle; implements a specification
Association classAn association that is also a class with its own attributes
Qualifier / qualified associationKey on an association end that partitions the linked set
Abstract classCannot be instantiated; name in italics or {abstract}
Interface«interface»: set of operations a classifier promises to provide
Enumeration«enumeration»: data type with a fixed set of literals
Stereotype / keyword / profileGuillemet tags extending (stereotype, via a profile) or built into (keyword) UML
ConstraintRule in braces, e.g. {qty > 0}, {ordered}
OCLObject Constraint Language (OMG, v2.4): invariants, pre- and postconditions
Instance specificationAn object on an object diagram: name : Type underlined, with slots
Package / «import» / «access» / «merge»Namespace; public import; private import; package merge
ComponentModular, replaceable unit with provided and required interfaces
Provided / required interfaceLollipop (ball) / socket; ball-in-socket = assembly connector
PortNamed interaction point on a classifier's boundary
Composite structureParts, ports and connectors inside one classifier
Node / device / execution environmentComputational resource on a deployment diagram (3D box)
Artifact / «manifest» / communication pathPhysical deliverable (binary, image, file); artifact embodies a component; link between nodes
Actor / use case / «include» / «extend»External role; user goal; mandatory reuse; conditional extension at an extension point
Action / control flow / object flow / object nodeActivity step; ordering edge; edge carrying data; data holder such as o : Order [paid]
Initial / activity final / flow finalStart dot; bullseye ending the whole activity; circled X ending one flow
Fork / join / decision / mergeSplit into concurrent flows / wait for all / choose by guard / rejoin without waiting
Activity partition (swimlane)Group of nodes with a common owner or location
State / composite state / region / orthogonal stateCondition of an object; state with substates; container of substates; state with several concurrent regions
Transition / trigger / guard / effectArrow between states; event; Boolean condition in [ ]; behaviour after /
entry / do / exitBehaviours run on entering, while in, and on leaving a state
PseudostateInitial, choice, junction, fork, join, entry/exit point, terminate, history
Shallow / deep history (H, H*)Re-enter last top-level substate / full last configuration
Time event / change eventafter(15 min) / when(condition)
LifelineParticipant in an interaction (vertical dashed line)
Execution specification (activation)Thin rectangle on a lifeline while it is executing
Synchronous / asynchronous / reply messageFilled head / open head / dashed line
Create / destroy (destruction occurrence)Dashed open-headed message to a new lifeline; X ending a lifeline
Lost / found messageKnown send, no receive / known receive, no known send
GateMessage end on the boundary of an interaction or fragment
Combined fragment / interaction operatorBox with alt, opt, loop, par, break, critical, neg, assert, seq, strict, ignore, consider
Interaction use (ref)Reference to another interaction
Communication diagramInteraction drawn on links with numbered messages (UML 1: collaboration diagram)
Interaction overview / timing diagramActivity of interactions / states on a time axis
Sketch / blueprint / programming languageFowler's three modes of using UML
Forward / reverse / round-trip engineeringDiagram → code / code → diagram / both kept in sync
MDAModel Driven Architecture, OMG's approach to generating code from models
XMI / UML DIXML interchange format for models / diagram interchange metamodel (Annex B)
PlantUMLText-to-diagram tool covering most UML diagrams (@startuml … @enduml)
MermaidMarkdown-inspired text-to-diagram tool rendered by GitHub; class, sequence, state, flowchart, C4
Diagrams as codeKeeping diagram sources as text in the repository, rendered on demand
C4 modelSimon Brown's context, container, component and code diagrams (+ landscape, dynamic, deployment)
Structural typing / implicit interface satisfactionGo: a type implements an interface by having its methods, without declaring it
Struct embeddingGo composition that promotes the embedded type's methods; not subtyping
Eloquent relationshipLaravel hasOne, hasMany, belongsTo, belongsToMany, morph*: associations with multiplicity
Pivot / withPivotLaravel's association class for many-to-many
ISO/IEC 19501 / 19505ISO publications of UML 1.4.x (2005) and UML 2 (2012)

References ​

Built by Morteza Negahi