# 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](https://help.gocapable.com/images/att1418035207.svg) 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 { <> +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. --- ## Related [Sequence diagramWho calls whom, in what order.](https://help.gocapable.com/diagrams/sequence-diagram.html) [Use case diagramActors, a boundary, and what the system does for them.](https://help.gocapable.com/diagrams/use-case-diagram.html) [UML diagramsBack to the UML overview.](https://help.gocapable.com/diagrams/uml-diagrams.html) --- _Four types cover most of it._