Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท From Models to Code

Class Diagrams to Code

Translate UML class diagrams into code: attributes, associations, multiplicity, composition, inheritance and interfaces, with a runnable Python generator.

A class diagram is only useful if the code ends up matching it. The translation is mostly mechanical, which is why code generators exist, but a developer still has to understand how each UML construct maps to a language, because the same arrow can be written in more than one way. This lesson lists the rules, shows the common choices, and builds a tiny generator so you see the mapping in action.

We use Python for the examples because it is short; the same rules apply to Java, C# and TypeScript with different syntax.

Classes, attributes and operations

A UML class box has three compartments: name, attributes and operations.

classDiagram
    class Account {
        -String id
        -double balance
        +deposit(amount) void
        +withdraw(amount) boolean
        +getBalance() double
    }

The rules:

  • The class name becomes a class.
  • An attribute becomes a field. Visibility - becomes private (_balance by convention in Python, private in Java), + public, # protected, ~ package.
  • An operation becomes a method; the return type and parameter types map to the language's types.
  • An underlined (static) member becomes a class-level member.
  • becomes a constant field or a property without a setter.
  • An abstract class or operation (italic name or ) becomes an abstract class or method.

Derived attributes (/age) are not stored; generate a computed property instead.

Associations and multiplicity

An association becomes a field in the class that navigates to the other. The rule depends on the navigability arrow and the multiplicity:

Diagram Code
Order --> Customer (one customer, 1) field customer of type Customer
Order --> Customer with 0..1 field that may be null: Customer | None
Order --> "*" Item a list/collection field items
bidirectional a field on each side; you must keep them consistent
association class a class between the two, holding the link's data

Bidirectional links are the main source of bugs: when you add an item to an order, the item's order field must change too. Write one method that updates both sides, and make the other side's setter private or package-level.

Aggregation and composition

  • Aggregation (hollow diamond) is a "has-a" without ownership. In code it is an ordinary reference to an object created elsewhere.
  • Composition (filled diamond) means ownership and shared lifetime. In code the owner creates the parts (inside its constructor or factory method) and nobody else keeps references to them. In languages without garbage collection, the owner also destroys them. In a database, composition maps to ON DELETE CASCADE.

Inheritance, interfaces and realization

A solid line with a hollow triangle is generalization: class Savings(Account). A dashed line with a hollow triangle is realization of an interface: class Savings(Account, Auditable) in Python, implements in Java. Multiple inheritance of classes may not be available (Java, C#); use interfaces and delegation there.

Dependencies

A dashed arrow means "uses temporarily": a parameter type, a local variable, a return type. It does not create a field. In code it is just an import and a use.

Enumerations and data types

<<enumeration>> becomes an enum. A <<dataType>> or value object becomes an immutable class or record.

A mapping you can run

The generator below takes a small model in plain dictionaries and emits Python code. It handles attributes, inheritance, collections and composition.

Python Generate Python from a model

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output is a skeleton; the developer still fills in method bodies. Real tools (and the model's own docs) call this forward engineering.

Keeping both ends of an association consistent

The mapping rule for bidirectional associations deserves its own example. One side owns the logic, the other side is updated by it.

Python A bidirectional one-to-many association

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The multiplicity 1 on the Order end is kept: an item is always in at most one order at a time.

Decisions the diagram does not make

A class diagram leaves gaps that the developer must fill consciously:

  1. Collection type: list, set, map? An ordered or property in the diagram answers it.
  2. Null handling: 0..1 should be reflected in types.
  3. Immutability and validation of attributes.
  4. Who creates whom: factories, constructors, dependency injection.
  5. Persistence mapping: tables, columns and cascades.

Write those decisions down as constraints or notes so the next reader knows they were deliberate.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How is a UML attribute with visibility - usually implemented?

    Minus means private. Languages without keywords use naming conventions such as a leading underscore.
  2. 2. Which code best matches a composition from Order to OrderLine?

    Composition means ownership and shared lifetime.
  3. 3. How should a 0..* association end usually appear in code?

    Multiplicity above one maps to a list, set or similar collection.
  4. 4. A dashed arrow from OrderService to Clock (a parameter type of one method) creates what in code?

    A dependency is a temporary use, not stored state.

Summary

  • Classes, attributes and operations map one to one to code constructs; visibility maps to access modifiers or conventions.
  • Associations become fields; multiplicity decides between a single reference, an optional one and a collection.
  • Composition means the owner creates and controls the parts; aggregation is a plain reference.
  • Generalization is inheritance, realization is implementing an interface, dependency is a temporary use.
  • The diagram leaves decisions open; record them as notes or constraints.

Next: State Machines to Code