Class diagram

A class diagram shows the structure of a model: what types exist, what they hold, and how they relate. It is most useful close to the code, and least useful as a whole-system drawing.

Draw the part of the model under discussion, not all of it.


#When to draw one

  • Explaining a domain model during design.

  • Documenting a library's public types.

  • Teaching, where the notation itself is the subject.


#What is on the diagram

Element

Meaning

Class

A type, with attributes and methods

Inheritance

A hollow triangle pointing at the parent

Composition

A filled diamond: the part cannot exist alone

Aggregation

A hollow diamond: the part can exist alone

Multiplicity

1, 0..1, 1..* on each end of an association


#A worked example

A small domain model with inheritance and composition:

Class diagram

The source, which you can paste into a new diagram and edit:

classDiagram
  class Order {
    +UUID id
    +OrderStatus status
    +Money total
    +addItem(Product, int)
    +submit()
  }
  class OrderItem {
    +int quantity
    +Money unitPrice
  }
  class Payment {
    <<abstract>>
    +Money amount
    +authorise()
  }
  class CardPayment
  class BankTransfer

  Order "1" *-- "1..*" OrderItem : contains
  Order "1" o-- "0..*" Payment : settled by
  Payment <|-- CardPayment
  Payment <|-- BankTransfer

#A few things that catch people out

  • Multiplicity is the part that carries information. Without it, an association says almost nothing.

  • Do not list every field. List the ones the reader needs to understand the relationships.

  • Class diagrams age badly. Keep them close to the code or regenerate them.



Four types cover most of it.