Read this post in: de_DEes_ESfr_FRhi_INid_IDjapl_PLpt_PTru_RUvizh_CNzh_TW

Comprehensive Guide to UML Class Diagrams (Diagram as Code)

💡 Note: All diagrams are provided in PlantUML format. You can render them instantly using the Visual Paradigm Diagram as Code.


🔹 Introduction to UML

What is UML?

“The Unified Modeling Language (UML) is a general-purpose visual modeling language that is used to specify, visualize, construct, and document the artifacts of a software system.” — Rumbaugh et al., 1999

Key Characteristics:

  • 🎨 Visual notation: Graphical syntax for modeling systems

  • 📐 Standardized: OMG-adopted standard since 1997

  • 🔧 Language, not a method: Defines notation, not process

  • 🌐 Broad scope: Models business processes, system functions, code structures, and database schemas

What UML Is NOT

Misconception Reality
A development methodology Just a modeling notation
A programming language Abstract specification language
Only for OO programming Applicable to databases, business modeling, etc.
Precisely defined in all aspects Some semantic ambiguities remain in early versions

🔹 History and Standardization

Evolution Timeline

Comprehensive Guide to UML Class Diagrams (Diagram as Code)

1965-1970: Simula-67 (first OO language)
     ↓
1970s-1980s: Smalltalk at Xerox PARC
     ↓
1984: C++ introduced by Bjarne Stroustrup
     ↓
1988-1992: Proliferation of OO methods (Booch, OMT, OOSE, etc.)
     ↓
1994: Rumbaugh joins Booch at Rational → Unification begins
     ↓
1995: UML 0.8 draft released
     ↓
1996: OMG issues RFP for standard modeling language
     ↓
1997: UML 1.1 adopted by OMG (November 14)
     ↓
2000: UML 1.3 formally published
     ↓
2003: UML 1.5 published; UML 2.0 superstructure accepted

Why UML Won the “Methods War”

  • Consolidated 50+ competing OO methods into one standard

  • Backed by major industry players (IBM, Microsoft, Oracle, HP)

  • Provided extension mechanisms for customization

  • Became the de facto standard for OO modeling

⚠️ Critical Perspective: Some argue UML is “a monster language designed by a committee” with imprecise semantics in early versions.


🔹 Classes and Attributes

Class Structure

A UML class is represented as a rectangle with up to three compartments.

@startuml
class Student {
  firstName: String
  lastName: String
  email[0..1]: String
  encryptedPW: String
  + totalPoints(): Integer
  + setPassword(pw: String)
  + checkPW(pw: String): Boolean
}
@enduml

Attribute Declaration Syntax

[visibility] name[multiplicity]: Type [= defaultValue] {properties}

PlantUML Examples:

@startuml
class Student {
  + ProgramOfStudy[0..2]: String = "MIS"
  - encryptedPW: String {frozen}
  # internalID: Integer
  ~ packagePrivateData: String
}
@enduml

Attribute Scope

  • Instance scope (default): Each object has its own value

  • Class scope (static): Single value shared by all instances

@startuml
class Student {
  name: String
  {static} count: Integer
}
@enduml

Keys in UML ⚠️

Important Limitation: UML has no built-in notion of keys. Use stereotypes or tagged values as workarounds.

@startuml
class Student {
  {pk} id: Integer
  {ak1} email: String
  - name: String
}
@enduml

🔹 Associations and Relationships

Basic Association & Multiplicity

@startuml
class Exercise
class Chapter
Exercise "0..*" -- "1..1" Chapter : BelongsTo
@enduml

Interpretation: Each exercise belongs to exactly one chapter; a chapter can contain zero or more exercises.

Role Names

Instead of (or in addition to) association names, use role names at association ends:

@startuml
class Person
class Company
Person "0..*" --> "0..1" Company : Employee/Employer
@enduml

Implementation: The Person table would have a foreign key employer referencing Company.

Navigability

Specify direction of traversal with arrows:

@startuml
class Exercise
class Chapter
Exercise "0..*" --> "1" Chapter
@enduml
  • Arrow indicates efficient traversal direction

  • In OODBs: implements as pointer in one direction only

  • In RDBMS: joins work both ways regardless

Collection Types with {ordered}

@startuml
class Chapter
class Exercise
Chapter "1" -- "0..*" Exercise : {ordered}
@enduml
  • {ordered}: Maintain sequence (use list, not set)

  • Implementation in RDBMS: Add sequence number attribute

EXERCISES (
    id PRIMARY KEY,
    chapter_id REFERENCES CHAPTERS,
    sort_no INTEGER,
    UNIQUE (chapter_id, sort_no)
)

Qualifiers

Qualifiers partition related objects using a key-like mechanism:

@startuml
class Chapter
class Exercise
Chapter "1" --> "0..1" Exercise : <<qualifier>> no: Integer
@enduml

Meaning: Given a Chapter and an exercise number, at most one Exercise is returned.

Association Classes

When an association has attributes or operations:

@startuml
class Student
class Exercise
class Solution {
  date: Date
  points: Integer
}
Student "0..*" -- "0..*" Exercise : has solved
Solution .. Student
Solution .. Exercise
@enduml
  • One Solution object per (Student, Exercise) pair

  • Enforces: same student cannot submit two solutions for same exercise

Composition vs. Aggregation

Feature Composition (*--) Aggregation (o--)
Symbol Black diamond White diamond
Relationship Whole-parts, strong ownership Whole-parts, weak reference
Lifecycle Parts deleted with whole Parts independent
Multiplicity 1 or 0..1 on whole side Any
RDBMS mapping ON DELETE CASCADE Standard foreign key
@startuml
class Chapter
class Exercise
Chapter *-- "0..*" Exercise : Composition
Chapter o-- "0..*" Exercise : Aggregation
@enduml

🔹 Operations and Methods

Operation Declaration Syntax

@startuml
class Calculator {
  + getTotal(studID: Integer, inclExtra: Boolean = true): Float {isQuery=true}
  + {static} getInstance(): Calculator
  + {constructor} Calculator(initialValue: Float)
  - recalculate(): void
}
@enduml

Parameter Specification:

[direction] name: Type [= defaultValue]
  • Directions: in (default), outinout

  • Default values enable optional parameters

Special Operation Stereotypes

Stereotype Purpose
{isQuery=true} Guarantees no state modification
{constructor} Creates and initializes new instances
{static} Class-level operation, no implicit self

Operations in Database Context

The Cultural Clash: OO emphasizes encapsulation; relational emphasizes direct data access.

Implementation Strategies:

Operation Type RDBMS Implementation
Simple attribute access Direct SELECT/UPDATE
Derived attribute (no params) Database VIEW
Derived attribute (with params) Stored procedure or application logic
Complex constraint enforcement Triggers or application procedures

🔹 Generalization and Inheritance

Basic Generalization

@startuml
class Person
class Student
class Professor
Person <|-- Student
Person <|-- Professor
@enduml

Abstract Classes and Operations

@startuml
abstract class Account {
  - balance: Float
  + deposit(amount: Float): void
  + {abstract} withdraw(amount: Float): void
}
@enduml

Generalization Constraints

@startuml
class Person
class Student
class Professor
class OtherPerson
Person <|-- Student : <<{disjoint, complete}>>
Person <|-- Professor : <<{disjoint, complete}>>
Person <|-- OtherPerson : <<{disjoint, complete}>>
@enduml

Multiple Classification / Discriminators

@startuml
class Employee
class Staff
class Faculty
class HMO
class NonHMO
Employee <|-- Staff : <<kind>>
Employee <|-- Faculty : <<kind>>
Employee <|-- HMO : <<insurance>>
Employee <|-- NonHMO : <<insurance>>
@enduml
  • Discriminators group mutually exclusive specializations

  • Objects can have one value per discriminator dimension


🔹 Extension Mechanisms

UML provides three extensibility mechanisms:

1. Stereotypes << >>

Extend UML semantics by creating new “subtypes” of metamodel elements.

@startuml
class Customer <<entity>> {
  - id: Integer
  - name: String
}
class MathLibrary <<utility>> {
  + sin(x: Float): Float
  + cos(x: Float): Float
}
@enduml

2. Tagged Values {key=value}

Add custom properties to model elements.

@startuml
class Student {
  {author=sb, version=1.0, persistence=persistent}
  - id: Integer
}
@enduml

3. Constraints {...}

Add semantic restrictions using free-form text, OCL, or predefined abbreviations.

@startuml
class Exercise {
  - no: Integer
  - points: Integer {value >= 0}
  {points <= maxPoints}
}
@enduml

🔹 UML for Database Design: Key Considerations

Translating UML to Relational Schema

UML Construct Relational Implementation
Class Table
Attribute Column
Primary key {pk} PRIMARY KEY constraint
Association (1:*) Foreign key on “many” side
Association (:) Junction/intersection table
Composition Foreign key + ON DELETE CASCADE
Association class Table with composite FKs + attributes
Generalization Separate tables (with FK) or single table with type discriminator
{ordered} association Add sequence column + unique constraint
Qualifier Part of composite key or indexed column

Critical Differences: OO vs. Relational

Aspect Object-Oriented Relational
Identity Object reference (surrogate) Primary key (business or surrogate)
Operations Core to design, encapsulated External (SQL, procedures)
Encapsulation Private attributes, public interface Direct table access by default
Inheritance Native language support Complex mapping strategies
Relationships Pointers/references Foreign keys and joins

Practical Recommendations for DB Designers

  1. Explicitly model keys: Use {pk}{ak1} stereotypes since UML lacks native key support

  2. Mark persistence: Use {persistent} tagged value to distinguish database classes from transient application classes

  3. Simplify operations: Map query operations to views; complex operations to stored procedures

  4. Handle inheritance carefully: Choose mapping strategy based on query patterns

  5. Document constraints: Use OCL or clear text constraints for business rules

  6. Use association classes judiciously: Only when relationship has significant attributes


🎯 Quick Reference Cheat Sheet

PlantUML Class Diagram Notation Summary

@startuml
class <<stereotype>> ClassName {
  {tagged=value}
  [+/-/#/~] name[mult]: Type [= val] {props}
  [+/-/#/~] name(params): Ret {props}
}
@enduml

Association Notation

@startuml
ClassA "multA" -- "multB" ClassB : AssociationName
ClassA *-- ClassB  ' Composition
ClassA o-- ClassB  ' Aggregation
ClassA --> ClassB  ' Navigable
@enduml

Visibility Symbols

  • + Public

  • - Private

  • # Protected

  • ~ Package

Common Properties & Constraints

  • {static} / {isQuery=true} / {abstract}

  • {value >= 0} / {xor} / {ordered} / {pk}


💡 Final Thought: UML class diagrams are powerful for conceptual modeling, but remember they were designed primarily for software engineering. When using UML for database design, be prepared to extend the notation (with stereotypes, tagged values, constraints) to capture relational concepts like keys, normalization, and declarative constraints that aren’t native to UML’s OO foundation.

Guide compiled from “Part 6: UML Class Diagrams” by Stefan Brass, Universität Halle, 2003. All diagrams formatted in PlantUML syntax for modern tooling compatibility.

Leave a Reply