UML Diagrams

📖 20 min read

The Unified Modeling Language (UML) is a standard graphical notation for describing software structure and behavior. It merged the object-oriented methods of Grady Booch, James Rumbaugh, and Ivar Jacobson at Rational Software in the mid-1990s and became an Object Management Group (OMG) standard in 1997. The current version, UML 2.5.1, was published in December 2017.

UML is large, and most teams use a small part of it. In Marian Petre’s 2013 interview study of 50 professional software engineers at 50 companies, 35 didn’t use UML at all, and among those who used it selectively, only one found use case diagrams useful. The practical skill is knowing which few diagrams answer which questions, and how much precision each one needs.

Sketch, Blueprint, or Program

Martin Fowler describes three ways teams use UML, and they call for very different levels of rigor.

Mode What the diagram is for Precision needed
Sketch Communicating or exploring one aspect of a design, on a whiteboard or in a document, then often discarded Only enough notation that readers interpret it the same way
Blueprint A detailed design someone else implements, or documentation of a system that has to stay accurate Complete and consistent within its scope
Programming language A model precise enough that tools generate executable code from it Formal, tool-checked

Most everyday value comes from sketches. A sequence diagram drawn to settle how a retry interacts with a timeout doesn’t need every arrowhead to be spec-exact, but it does need a solid line to mean a call and a dashed line to mean a return, so that readers don’t argue about what it says. Blueprint use persists where contracts or regulation demand design documentation. Generating code from models, once promoted as model-driven architecture, survives mainly in specialized domains such as embedded and safety-critical systems.

The Fourteen Diagram Types

UML 2.5.1 defines fourteen diagram types, split between structure (what the system is made of) and behavior (what it does over time).

Group Diagram Shows Everyday use
Structure Class Types, their attributes and operations, and relationships Common
Structure Object Specific instances and their links at one moment Occasional, to illustrate a tricky class diagram
Structure Package Grouping of model elements and dependencies between groups Occasional
Structure Composite structure Internal parts and connectors of a class or component Rare
Structure Component Replaceable parts with provided and required interfaces Occasional
Structure Deployment Artifacts placed on nodes and communication paths Occasional
Structure Profile Extensions of UML itself through stereotypes Rare, for tool builders
Behavior Use case Actors and the goals the system serves for them Occasional
Behavior Activity Flow of actions, decisions, and parallel work Common
Behavior State machine States of one object and the events that move it between them Common for stateful entities
Interaction Sequence Messages between participants in time order Common
Interaction Communication The same messages as a sequence diagram, arranged by links instead of time Rare
Interaction Interaction overview An activity-style flow whose nodes are interactions Rare
Interaction Timing State changes of participants against a time axis Rare, mostly real-time and embedded

Interaction diagrams are a subgroup of behavior diagrams. The rest of this guide covers the seven in bold.

Structure Diagrams

Class Diagrams

A class diagram shows types, what each holds and can do, and how they relate. The same diagram can be drawn from three perspectives, and the perspective decides how much detail belongs on it.

Structure

Three Perspectives on One Class

One Order class as concept, as interface, and as code.

Three Perspectives on One Class The same Order class drawn as a domain concept, as an interface, and as the code, with detail added at each step. CONCEPTUAL domain concepts, no types Order placed on total lines SPECIFICATION the interface, no implementation Order + PlacedOn : DateTime + Total : Money + AddLine(item, qty) : void + Cancel() : void IMPLEMENTATION mirrors the code Order - _id : Guid - _lines : List<OrderLine> - _placedOn : DateTime + Total : Money { get; } + Order(Guid id) + AddLine(CatalogItem, int) : void - Recalculate() : void + Cancel() : void The perspective decides how much detail belongs on the diagram. Implementation views drift from the code within weeks, so generate them or draw at one of the other two perspectives instead.

A conceptual class diagram names domain concepts and their relationships, with little or no attribute detail. It suits early discussion of a domain with people who don’t read code. A specification diagram adds types and operation signatures, describing interfaces without committing to an implementation. An implementation diagram mirrors the code, including defaults and every accessor. Implementation diagrams go stale fastest, and when needed they are usually better generated from the code than drawn.

Each class is a box with up to three compartments for name, attributes, and operations. Members carry a visibility marker, which is + for public, - for private, # for protected, and ~ for package. Operation parameters can state a direction, in, out, or inout, which matters when a sketch documents an API whose parameters are modified in place.

Structure

Class Notation

The compartments, visibility markers, and parameter directions of a class box.

Class Notation What each compartment of a class box holds, what the visibility markers mean, and how a parameter states its direction. CatalogItem + Sku : string - _price : Money # Category : string ~ Warehouse : string + Reprice(in Money newPrice) : void + TrySplit(out CatalogItem half) : bool + Merge(inout Stock level) : void the class name attributes, each with a visibility marker: + public − private # protected ~ package operations, whose parameters can state a direction: in, out, or inout Leave out any compartment, and any member, that does not serve the point the diagram is making.

Six relationship lines carry most of a class diagram’s meaning:

Rules

Class Relationship Notation

The six relationship lines and their arrowheads and diamonds.

Class Relationship Notation The six lines that carry most of a class diagram’s meaning, drawn with the arrowhead or diamond that distinguishes each one. Order Customer 1 0..* Association one type holds or references the other CardPayment Payment Generalization the child is a kind of the parent CardPayment IPayable Realization the class implements the interface Order PriceRule Dependency one uses the other without holding it OrderLine Basket Aggregation parts can exist without the whole OrderLine Order Composition the part dies with its one whole The specification leaves aggregation’s meaning open, so readers read the hollow diamond differently.
Relationship Notation Meaning
Association Solid line, optionally with an open arrowhead for navigability Instances of one type hold or reference instances of the other
Generalization (inheritance) Solid line, hollow triangle at the parent The child is a kind of the parent
Realization Dashed line, hollow triangle at the interface The class implements the interface
Dependency Dashed line, open arrowhead One type uses the other, for example as a parameter, without holding it
Aggregation Solid line, hollow diamond at the whole A whole-part association where parts can exist independently
Composition Solid line, filled diamond at the whole A part belongs to one whole at a time, and is deleted with it

Associations also carry multiplicity at each end, such as 1, 0..1, *, or 1..*, which states how many instances take part. The UML specification itself notes that the precise meaning of aggregation varies by application area and modeler, so teams often skip it and use a plain association, reserving the diamond for composition, where the lifetime rule is unambiguous.

A fuller diagram combines these, and can also use stereotypes such as «entity» and «interface» to mark the role each class plays, and an italic name to mark an abstract class:

Structure

Class Diagram for the Order Domain

The order domain with all six relationship kinds.

Class Diagram for the Order Domain One subsystem drawn with all six relationship kinds, showing only the members that matter to the point the diagram makes. «interface» IPayable + Authorize(Money) : bool Payment {abstract} + Amount : Money + Authorize(Money) : bool CardPayment + Last4 : string «entity» Customer + Id : Guid + Name : string «entity» Order + PlacedOn : DateTime + Status : OrderStatus + Total() : Money «entity» OrderLine + Quantity : int + UnitPrice : Money CatalogItem + Sku : string + Price : Money Basket + AddedOn : DateTime «uses» 1 0..* 1 1..* 0..* 1 1 0..* 1 0..1 Stereotypes such as «entity» and «interface» mark the role a class plays, and an italic name marks an abstract class.

A class diagram earns its place for a core domain model whose relationships and multiplicities are the design, or for an unfamiliar area of code that a newcomer needs mapped. Keeping it focused on one subsystem, and showing only the members that matter to the point being made, keeps it readable.

Component Diagrams

A component diagram shows replaceable parts of a system and the interfaces that connect them. A provided interface is drawn as a circle, or lollipop, and a required interface as a half-circle socket. Where one component’s socket meets another’s lollipop, the dependency is satisfied. Ports are small squares on a component’s boundary where interfaces attach, which lets a component expose an interface that is implemented by a part inside it.

Structure

Component Notation

Lollipop, socket, and port notation on one component.

Component Notation The lollipop, socket, and port notation that says which interfaces a component provides, which it requires, and where they attach. «component» Terminal SafetyInspection «component» Staff «component» Defect «component» Map «component» provided interface (lollipop) «IInspection» required interface (socket) «IStaffDirectory» port: where an interface meets the component boundary A delegation connector routes a port through to the part inside that implements the interface. Where one component’s socket meets another’s lollipop, the dependency is satisfied.
Structure

Component Diagram for Online Store

Five components of the Online Store and their interfaces.

Component Diagram for Online Store Five replaceable parts of one system and the interfaces that connect them, which is the design decision a component diagram exists to record. «component» StoreFront customer-facing UI «component» Checkout basket and payment «component» Catalogue products and prices «component» OrderSystem places and tracks orders «component» PaymentAdapter wraps the gateway SDK «ICatalogue» «IOrders» «IAuthorize» A socket meeting a lollipop means the required interface is satisfied. Ports are where an interface attaches to the boundary.

Component diagrams are most useful when the interfaces between parts are the design decision, such as a plugin system, a set of modules with enforced boundaries, or a replacement plan for one part of a larger system. For showing how a system’s applications, services, and data stores communicate, many teams now draw architecture-level structure views such as C4 container diagrams instead, which carry technology and protocol labels that UML component diagrams leave out.

Deployment Diagrams

A deployment diagram shows nodes, drawn as three-dimensional boxes, which represent hardware devices or execution environments such as a server, a virtual machine, a container runtime, or a database server. Artifacts, such as an executable, a container image, or a configuration file, are deployed onto nodes. Communication paths between nodes show which can talk to which.

C4 · Deployment

Deployment Diagram for Online Store

Artifacts on nodes, with protocols and network zones.

Deployment Diagram for Online Store Which artifacts run on which nodes, the protocol on every communication path, and the network zone each node sits in. PUBLIC INTERNET PRIVATE SUBNET «device» Client device «artifact» store.spa.js «execution environment» App server × 3 «artifact» orders-api.dll «artifact» worker.dll «device» Database server «artifact» orders.schema «device» Cache node × 2 redis.conf «HTTPS» «TCP/IP, TLS» «TCP» Nodes are devices or execution environments. Artifacts are what gets deployed onto them. Naming the protocol on each path and marking the network zones adds more than drawing every node.

The diagram helps when placement is what’s being decided, such as which tier sits in which network zone, where a cache lives relative to the servers that read it, or which environments exist. It stops helping once it tries to capture everything a cloud infrastructure-as-code template already records. Labeling paths with protocols and marking security boundaries tends to add more than drawing every node.

Behavior Diagrams

Sequence Diagrams

A sequence diagram shows participants as lifelines, vertical dashed lines headed by a name, with messages as horizontal arrows ordered top to bottom in time. A thin bar on a lifeline, the activation, shows when that participant is executing.

C4 · Dynamic

Sequence Diagram for Checkout

One checkout scenario with activations, fragments, and a destroyed lifeline.

Sequence Diagram for Checkout One checkout scenario in message order, with activations, a self message, loop and alt fragments, and a lifeline created and destroyed. :Customer :Checkout :OrdersApi :PaymentGw :Order checkout() POST /orders validate() «create» loop [each order line] addLine(item, qty) alt [funds available] authorize(total) approved [declined] «destroy» 201 Created confirmation page A filled arrowhead is a synchronous call, a dashed line a reply, a dashed line to a new head a creation, and an X the end of a lifeline. One scenario per diagram, including the error path that prompted it.

The arrow style carries meaning:

Notation Meaning
Solid line, filled arrowhead Synchronous call, the sender waits
Solid line, open arrowhead Asynchronous message, the sender continues
Dashed line, open arrowhead Reply to an earlier call
Dashed line to the head of a new lifeline Creation of that participant
An X at the bottom of a lifeline Destruction of that participant

Combined fragments are labeled frames that add control flow. alt shows alternatives with guards, opt an optional section, loop repetition, par parallel sections, and break an early exit. A ref frame points to another sequence diagram, so one large flow can be split into readable parts.

Sequence diagrams suit flows where the order of messages is the question, such as an authentication handshake, a saga’s compensation path, or how retries and timeouts interact across three services. One scenario per diagram, including the error path that prompted the diagram in the first place, keeps them readable. A diagram that tries to show every branch in alt frames tends to become harder to follow than the code.

Activity Diagrams

An activity diagram shows a flow of actions, closer to a flowchart than any other UML diagram but able to show parallel work. It starts at a filled initial node and ends at a bullseye activity final node. Rounded rectangles are actions. A diamond is a decision when one flow enters and guarded flows leave, and a merge when several alternative flows rejoin. A thick bar is a fork when it splits one flow into parallel flows, and a join when it waits for parallel flows to finish.

Rules

Activity Diagram Notation

The glyphs of an activity diagram, including decision versus merge.

Activity Diagram Notation The glyphs an activity diagram is built from, and the distinction between a decision and a merge, and between a fork and a join. initial node Receive order decision [in stock] [else] Reserve stock Backorder item merge Charge card fork Pack items Email receipt join activity final A diamond is a decision when one flow enters and guarded flows leave, and a merge when alternatives rejoin. A bar is a fork when it splits one flow into parallel flows, and a join when it waits for all of them. Using a join where the branches are alternatives describes a process that never completes.

The distinction between a merge and a join has consequences. A merge passes along whichever single branch arrives, while a join waits for all of its parallel inputs. Using a join where branches are alternatives describes a process that never completes.

Flow

Activity Diagram for Order Fulfilment

Order fulfilment with a decision, a fork, and a join.

Activity Diagram for Order Fulfilment One business workflow with a decision, a parallel fork and join, and every path reaching an end. Receive order Check stock [else] Backorder and notify [in stock] Reserve stock Charge card Pack and ship Every action names what is done, not who does it. The partitioned version of this same flow adds the roles to it. A merge passes along whichever branch arrives; a join waits for all of its parallel inputs.

Partitions, commonly called swimlanes, assign each action to the role or system that performs it. Handoffs between partitions are where delays and errors often concentrate in a business process, so swimlanes make them visible.

Flow

The Same Flow, Partitioned

The same flow in partitions, one per role.

The Same Flow, Partitioned The order fulfilment flow divided into partitions, so that every action says which role performs it and every handoff is visible. CUSTOMER SERVICE WAREHOUSE FINANCE Receive order Check stock [in stock] Reserve stock [else] Backorder and notify Charge card Pack and ship Handoffs between partitions are where delays and errors concentrate, which is what the lanes make visible.

Activity diagrams fit business workflows, multi-step jobs with parallel branches, and approval processes, especially when non-developers need to validate the flow. Teams modeling business processes alone often use BPMN instead, which covers similar ground with notation that business analysts more commonly know.

State Machine Diagrams

A state machine diagram shows the states one object moves through and the events that move it. Each transition is labeled trigger [guard] / effect, where the trigger is the event, the guard is a condition that must hold, and the effect is what happens during the transition. A filled circle marks the initial state and a bullseye a final state.

State machine

State Machine for an Order

The states of an order and the events between them.

State Machine for an Order The states an order moves through, the events that move it, and the transitions that are deliberately absent. place order Pending Paid entry / reserveStock Shipped Cancelled Delivered paymentReceived [stock available] / reserveStock dispatched / notifyCustomer cancel cancel / refundPayment delivered No cancel transition leaves Shipped, so an order cannot be cancelled after dispatch. The diagram shows as much by what is missing. Each transition reads trigger [guard] / effect, and each one maps to a test.

The diagram shows as much by what’s missing as by what’s drawn. There is no cancel transition from Shipped, so an order can’t be cancelled after dispatch, and a paymentReceived event while stock is unavailable leaves the order in Pending. States can also declare entry, exit, and do behaviors, and a composite state can contain its own nested state machine.

State machine diagrams tend to stay accurate longer than most UML diagrams, because the states and transitions of an order, a payment, a subscription, or a workflow are business rules that change far less often than the code implementing them. They also map directly to tests, one per transition plus one per event that should be rejected in each state.

Use Case Diagrams

A use case diagram shows actors, the people or external systems that interact with the system, drawn as stick figures, and use cases, the goals the system fulfills for them, drawn as ovals inside a system boundary. Lines associate actors with the use cases they take part in.

Structure

Use Case Notation

Actors, use cases, and the system boundary.

Use Case Notation Actors, the goals the system serves for them, and the boundary that says which goals are inside the system being scoped. ONLINE STORE Browse catalogue Place order Track shipment Customer Courier API «system actor» An actor is a role, not a person: one human may play several, and an external system can be an actor. The ovals are a table of contents. The requirements live in the written use case behind each one.

Three relationships connect use cases and actors. Include is a dashed arrow from a base use case to behavior it always performs, factored out because several use cases share it. Extend is a dashed arrow from an optional use case to the base use case it can add behavior to, at a named extension point, under some condition. Generalization makes one actor or use case a specialized kind of another. The arrows point in opposite directions for include and extend, which is the most common error on these diagrams.

Rules

Include, Extend, and Generalization

Which way include, extend, and generalization each point.

Include, Extend, and Generalization Which way each of the three use case relationships points, and what the arrow direction means in each case. Place order Authenticate «include» points to the behaviour the base always performs Place order Apply coupon «extend» [discount code entered] points to the use case being extended, under a condition Pay Pay by card generalization the specialized one points at the general one The arrows for include and extend point in opposite directions, which is the most common error on these diagrams.

The diagram is a table of contents. The requirements live in the written use case behind each oval, with its main success scenario, alternatives, and failure handling. A use case diagram helps scope a system with stakeholders, and it adds little once that scope is agreed, which fits Petre’s finding that practitioners rarely find it useful on its own.

Choosing a Diagram

Starting from the question, rather than from the diagram types, avoids drawing diagrams nobody needed.

Question Diagram
What are the core domain concepts and how are they related? Class, conceptual perspective
What does this module’s public API look like? Class, specification perspective
In what order do these participants call each other, and what happens on failure? Sequence
Which states can this entity be in, and what moves it between them? State machine
What are the steps of this process, who does each, and what runs in parallel? Activity with partitions
Which parts can be replaced independently, and through which interfaces? Component
What runs where, and which nodes can talk to each other? Deployment
What goals does the system serve, and for whom? Use case, backed by written use cases

Keeping Diagrams Useful

Text-based tools make UML diagrams reviewable alongside code. PlantUML covers most UML diagram types from a text description, and Mermaid renders class, sequence, and state diagrams inline in Markdown on platforms that support it. The source lives in version control, so a change to a diagram shows up in a pull request next to the code it describes. Graphical modeling tools remain useful for blueprint-mode work where a model is shared across many diagrams.

Generating diagrams from code, which many IDEs and modeling tools can do for class and dependency views, keeps implementation-level diagrams accurate at no maintenance cost. Hand-drawn diagrams are better reserved for what code can’t show directly, such as intended states and transitions, a flow across services, or a conceptual model.

Common Pitfalls

  • Modeling everything. Diagrams of simple, well-understood code cost time to draw and maintain and tell readers nothing the code doesn’t. Focus on complex, risky, or frequently misunderstood areas.
  • Implementation-level class diagrams drawn by hand. They drift from the code within weeks. Generate them, or draw at the conceptual or specification perspective instead.
  • One sequence diagram for every path. Nested alt frames covering every branch are harder to read than the code. Draw the main scenario and the one error path that matters.
  • Join bars used as merges. An activity diagram that joins alternative branches describes a process that waits forever.
  • Reversed include and extend arrows. Include points to the shared behavior. Extend points to the use case being extended.
  • Aggregation used without agreement on its meaning. The specification leaves its semantics open, so readers interpret the hollow diamond differently. Use a plain association or composition.
  • Precise notation for a sketch, or loose notation for a blueprint. A whiteboard sketch doesn’t need every stereotype, and a design handed to another team can’t rely on arrowheads readers have to guess at.

Quick Reference

Diagram Key notation Best for
Class Compartments, visibility, association, generalization, composition, multiplicity Domain models, API shape
Component Provided and required interfaces, ports Module boundaries, plugin architectures
Deployment Nodes, artifacts, communication paths Placement and network zone decisions
Sequence Lifelines, sync and async messages, combined fragments Cross-service flows, protocols, error paths
Activity Actions, decision and merge, fork and join, partitions Business processes, parallel workflows
State machine States, trigger [guard] / effect transitions Order, payment, and workflow lifecycles
Use case Actors, use cases, include, extend, system boundary Scoping with stakeholders

Found this guide helpful? Share it with your team:

Share on LinkedIn