Skip to main content

Composition — Has-A with Dependent Lifecycle

Editorial

Introduction

A university opens its departments. Computer Science, Mathematics and Physics exist because the university made them, and if the university closes, they close with it. A department does not move to another university and carry on; it ends with the university that made it.

That relationship is called composition: the whole owns its parts, and when the whole ends, its parts end with it. It is the strongest kind of has-a relationship. Aggregation — Has-A with Independent Lifecycle showed the other kind, a department holding professors who live on without it. The same university shows both: it owns its departments, and each department holds professors it does not own.

You will also meet the advice to favor composition over inheritance, in Composition vs Inheritance — Favor Composition. There the word has a wider meaning: building an object out of other objects it holds, whatever their lifecycles. This page is about the narrower meaning UML gives it.

Composition and Aggregation

Composition and aggregation are both associations between a whole and its parts. They differ in what happens to the parts when the whole ends, and in how many wholes a part can belong to.

UML gives composition firm rules. "If a composite object is deleted, all of its part instances that are objects are deleted with it." A part also belongs to one whole at a time: composite aggregation "requires a part object be included in at most one composite object at a time". And a part may leave before the end: "A part object may (where otherwise allowed) be removed from a composite object before the composite object is deleted", and then it is not deleted with it.

Aggregation has none of these rules. A department's professors survive it, and one professor can be in two departments at once.

Some cases of each:

  • A house has rooms: composition. Demolish the house and its rooms go with it.
  • A car has an engine: composition. The engine was built for that car and is scrapped with it, unless it is taken out first.
  • An order has order items: composition. "Item 3 of order 5001" means nothing without order 5001.
  • A body has a heart: composition. A heart can still be taken out first, for a transplant, which is the part leaving before the whole ends.
  • A team has players: aggregation. The players stay when the team breaks up and can join another.

UML Notation

Here is the notation, with the code tell, the comparison and some everyday compositions:

Composition, the strongest has-a relationship: the whole owns its parts, and when the whole dies the parts die with it. UML notation, with the filled diamond on the whole's side and an arrow to the part: University owns Department and Order owns OrderItem, each with multiplicity 1 at the whole and * at the part; inside the university, Department has Professor, an aggregation with a hollow diamond and * at both ends, so closing the university ends its departments and not the professors they held. The code tell, who makes the part: aggregation makes it outside and hands it in (smith = Professor("Smith", "Algorithms"); cs = Department("Computer Science"); cs.add_professor(smith)); composition makes it inside the whole (riverside = University("Riverside University"); riverside.open_department("Computer Science")). Destroy the whole: are its parts destroyed too? Aggregation: lifecycle, parts survive the whole; ownership, a part may be in many wholes; making, made outside and handed in. Composition: lifecycle, parts end with the whole; ownership, one whole at a time; making, made by (or for) the whole. Yes means composition, no means aggregation; in a database, composition is ON DELETE CASCADE. Real-world compositions drawn the same way: House owns Room, Car owns Engine, Order owns OrderItem, Body owns Heart.

The filled diamond sits at the whole's end of the line, here at University and at Order, and the arrowhead points at the part. The whole's end says 1: a department belongs to exactly one university, and UML does not allow more than one at a composite end. The part's end says *, because a university starts with no departments and can lose them all.

Inside the university, each department holds its professors by aggregation, drawn with a hollow diamond. When the university closes, its departments end, and the professors they held do not.

Watch a University Close

The interactive runs the university's calls from the listing: three departments opened, Smith hired into Computer Science, then the university closed. The departments are drawn inside the university that owns them. Watch them end with it, while Smith stays.

The university's calls from the listing. Its departments sit inside it; closing the university ends them and leaves Smith.

Code Example

Here is a university and an order in code. The university makes its departments inside open_department, keeps them in a list it never hands out, and ends them all in close. Smith is made outside and handed to a department, as in Aggregation — Has-A with Independent Lifecycle. The order makes its items in add_item and ends them in cancel. Prices are kept in whole cents, so every language prints the same totals:

class Professor:
    def __init__(self, name: str, specialization: str) -> None:
        self._name = name
        self._specialization = specialization

    @property
    def name(self) -> str:
        return self._name

    def describe(self) -> str:
        return f"Prof. {self._name} ({self._specialization})"


class Department:
    # Only a University makes a Department: a part that lives inside one whole
    def __init__(self, name: str) -> None:
        self._name = name
        # aggregation: its professors are handed in, never made here
        self._professors: list[Professor] = []

    @property
    def name(self) -> str:
        return self._name

    def add_professor(self, professor: Professor) -> None:
        self._professors.append(professor)
        print(f"  {professor.name} joined {self._name}")

    def headcount(self) -> int:
        return len(self._professors)

    def close(self) -> None:
        self._professors.clear()  # its professors are let go, not ended
        print(f"  {self._name} closed")


class University:
    def __init__(self, name: str) -> None:
        self._name = name
        # composition: the university makes its departments and hands none of them out
        self._departments: list[Department] = []

    def open_department(self, name: str) -> None:
        self._departments.append(Department(name))
        print(f"  {self._name} opened {name}")

    def hire(self, department_name: str, professor: Professor) -> None:
        for dept in self._departments:
            if dept.name == department_name:
                dept.add_professor(professor)

    def show(self) -> None:
        parts = ", ".join(f"{d.name} ({d.headcount()})" for d in self._departments)
        print(f"  {self._name}: {parts or 'no departments'}")

    # Closing the whole ends every part: no department outlives its university
    def close(self) -> None:
        count = len(self._departments)
        for dept in self._departments:
            dept.close()
        self._departments.clear()
        print(f"  {self._name} closed: {count} departments went with it")


def money(cents: int) -> str:
    return f"{cents // 100}.{cents % 100:02d}"


class OrderItem:
    def __init__(self, product: str, quantity: int, unit_cents: int) -> None:
        self._product = product
        self._quantity = quantity
        self._unit_cents = unit_cents

    def describe(self) -> str:
        return f"{self._product} x{self._quantity}"

    def subtotal(self) -> int:
        return self._quantity * self._unit_cents


class Order:
    def __init__(self, order_id: str) -> None:
        self._order_id = order_id
        self._items: list[OrderItem] = []  # composition: made here, ended here

    def add_item(self, product: str, quantity: int, unit_cents: int) -> None:
        item = OrderItem(product, quantity, unit_cents)
        self._items.append(item)
        print(f"  Added {item.describe()} to {self._order_id}")

    def total(self) -> int:
        return sum(item.subtotal() for item in self._items)

    def show(self) -> None:
        count = len(self._items)
        print(f"  {self._order_id}: {count} items, total {money(self.total())}")

    def cancel(self) -> None:
        count = len(self._items)
        self._items.clear()
        print(f"  {self._order_id} cancelled: {count} items went with it")


print("Founding:")
riverside = University("Riverside University")
riverside.open_department("Computer Science")
riverside.open_department("Mathematics")
riverside.open_department("Physics")
smith = Professor("Smith", "Algorithms")  # made outside, as in aggregation
riverside.hire("Computer Science", smith)
riverside.show()

print("Closing:")
riverside.close()
riverside.show()
print(f"  Still here: {smith.describe()}")

print("Ordering:")
order = Order("ORD-5001")
order.add_item("Laptop", 1, 99999)
order.add_item("Mouse", 2, 2999)
order.add_item("USB Cable", 3, 999)
order.show()

print("Cancelling:")
order.cancel()
order.show()
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class Professor {
    private final String name;
    private final String specialization;

    public Professor(String name, String specialization) {
        this.name = name;
        this.specialization = specialization;
    }

    public String getName() {
        return name;
    }

    public String describe() {
        return "Prof. " + name + " (" + specialization + ")";
    }
}

// Only a University makes a Department: a part that lives inside one whole
class Department {
    private final String name;
    // aggregation: its professors are handed in, never made here
    private final List<Professor> professors = new ArrayList<>();

    Department(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void addProfessor(Professor professor) {
        professors.add(professor);
        System.out.println("  " + professor.getName() + " joined " + name);
    }

    public int headcount() {
        return professors.size();
    }

    public void close() {
        professors.clear(); // its professors are let go, not ended
        System.out.println("  " + name + " closed");
    }
}

class University {
    private final String name;
    // composition: the university makes its departments and hands none of them out
    private final List<Department> departments = new ArrayList<>();

    public University(String name) {
        this.name = name;
    }

    public void openDepartment(String deptName) {
        departments.add(new Department(deptName));
        System.out.println("  " + name + " opened " + deptName);
    }

    public void hire(String departmentName, Professor professor) {
        for (Department dept : departments) {
            if (dept.getName().equals(departmentName)) {
                dept.addProfessor(professor);
            }
        }
    }

    public void show() {
        String parts = departments.stream()
                .map(d -> d.getName() + " (" + d.headcount() + ")")
                .collect(Collectors.joining(", "));
        System.out.println("  " + name + ": "
                + (parts.isEmpty() ? "no departments" : parts));
    }

    // Closing the whole ends every part: no department outlives its university
    public void close() {
        int count = departments.size();
        for (Department dept : departments) {
            dept.close();
        }
        departments.clear();
        System.out.println("  " + name + " closed: " + count
                + " departments went with it");
    }
}

class OrderItem {
    private final String product;
    private final int quantity;
    private final int unitCents;

    OrderItem(String product, int quantity, int unitCents) {
        this.product = product;
        this.quantity = quantity;
        this.unitCents = unitCents;
    }

    public String describe() {
        return product + " x" + quantity;
    }

    public int subtotal() {
        return quantity * unitCents;
    }
}

class Order {
    private final String orderId;
    // composition: made here, ended here
    private final List<OrderItem> items = new ArrayList<>();

    public Order(String orderId) {
        this.orderId = orderId;
    }

    public void addItem(String product, int quantity, int unitCents) {
        OrderItem item = new OrderItem(product, quantity, unitCents);
        items.add(item);
        System.out.println("  Added " + item.describe() + " to " + orderId);
    }

    public int total() {
        return items.stream().mapToInt(OrderItem::subtotal).sum();
    }

    public void show() {
        int count = items.size();
        System.out.println("  " + orderId + ": " + count + " items, total "
                + money(total()));
    }

    public void cancel() {
        int count = items.size();
        items.clear();
        System.out.println("  " + orderId + " cancelled: " + count
                + " items went with it");
    }

    static String money(int cents) {
        return cents / 100 + "." + String.format("%02d", cents % 100);
    }
}

public class CompositionDemo {
    public static void main(String[] args) {
        System.out.println("Founding:");
        University riverside = new University("Riverside University");
        riverside.openDepartment("Computer Science");
        riverside.openDepartment("Mathematics");
        riverside.openDepartment("Physics");
        // made outside, as in aggregation
        Professor smith = new Professor("Smith", "Algorithms");
        riverside.hire("Computer Science", smith);
        riverside.show();

        System.out.println("Closing:");
        riverside.close();
        riverside.show();
        System.out.println("  Still here: " + smith.describe());

        System.out.println("Ordering:");
        Order order = new Order("ORD-5001");
        order.addItem("Laptop", 1, 99999);
        order.addItem("Mouse", 2, 2999);
        order.addItem("USB Cable", 3, 999);
        order.show();

        System.out.println("Cancelling:");
        order.cancel();
        order.show();
    }
}
#include <cstdio>
#include <string>
#include <vector>

class Professor {
public:
    Professor(std::string name, std::string specialization)
        : name_(std::move(name)), specialization_(std::move(specialization)) {}

    const std::string& getName() const { return name_; }

    std::string describe() const {
        return "Prof. " + name_ + " (" + specialization_ + ")";
    }

private:
    std::string name_;
    std::string specialization_;
};

// Only a University makes a Department: a part that lives inside one whole
class Department {
public:
    explicit Department(std::string name) : name_(std::move(name)) {}

    const std::string& getName() const { return name_; }

    void addProfessor(Professor& professor) {
        professors_.push_back(&professor);
        std::printf("  %s joined %s\n", professor.getName().c_str(), name_.c_str());
    }

    int headcount() const { return static_cast<int>(professors_.size()); }

    void close() {
        professors_.clear();  // its professors are let go, not ended
        std::printf("  %s closed\n", name_.c_str());
    }

private:
    std::string name_;
    // aggregation: its professors are handed in, never made here
    std::vector<Professor*> professors_;
};

class University {
public:
    explicit University(std::string name) : name_(std::move(name)) {}

    void openDepartment(const std::string& deptName) {
        departments_.emplace_back(deptName);
        std::printf("  %s opened %s\n", name_.c_str(), deptName.c_str());
    }

    void hire(const std::string& departmentName, Professor& professor) {
        for (Department& dept : departments_) {
            if (dept.getName() == departmentName) {
                dept.addProfessor(professor);
            }
        }
    }

    void show() const {
        std::string parts;
        for (const Department& d : departments_) {
            parts += (parts.empty() ? "" : ", ") + d.getName() + " ("
                     + std::to_string(d.headcount()) + ")";
        }
        std::printf("  %s: %s\n", name_.c_str(),
                    parts.empty() ? "no departments" : parts.c_str());
    }

    // Closing the whole ends every part: no department outlives its university
    void close() {
        int count = static_cast<int>(departments_.size());
        for (Department& dept : departments_) {
            dept.close();
        }
        // the vector holds the departments themselves, so clearing it destroys them
        departments_.clear();
        std::printf("  %s closed: %d departments went with it\n", name_.c_str(), count);
    }

private:
    std::string name_;
    // composition: the university makes its departments and hands none of them out
    std::vector<Department> departments_;
};

std::string money(int cents) {
    std::string rest = std::to_string(cents % 100);
    return std::to_string(cents / 100) + "." + (rest.size() < 2 ? "0" : "") + rest;
}

class OrderItem {
public:
    OrderItem(std::string product, int quantity, int unitCents)
        : product_(std::move(product)), quantity_(quantity), unitCents_(unitCents) {}

    std::string describe() const { return product_ + " x" + std::to_string(quantity_); }

    int subtotal() const { return quantity_ * unitCents_; }

private:
    std::string product_;
    int quantity_;
    int unitCents_;
};

class Order {
public:
    explicit Order(std::string orderId) : orderId_(std::move(orderId)) {}

    void addItem(const std::string& product, int quantity, int unitCents) {
        items_.emplace_back(product, quantity, unitCents);
        std::printf("  Added %s to %s\n", items_.back().describe().c_str(),
                    orderId_.c_str());
    }

    int total() const {
        int sum = 0;
        for (const OrderItem& item : items_) {
            sum += item.subtotal();
        }
        return sum;
    }

    void show() const {
        int count = static_cast<int>(items_.size());
        std::printf("  %s: %d items, total %s\n", orderId_.c_str(), count,
                    money(total()).c_str());
    }

    void cancel() {
        int count = static_cast<int>(items_.size());
        items_.clear();
        std::printf("  %s cancelled: %d items went with it\n", orderId_.c_str(), count);
    }

private:
    std::string orderId_;
    std::vector<OrderItem> items_;  // composition: made here, ended here
};

int main() {
    std::printf("Founding:\n");
    University riverside("Riverside University");
    riverside.openDepartment("Computer Science");
    riverside.openDepartment("Mathematics");
    riverside.openDepartment("Physics");
    Professor smith("Smith", "Algorithms");  // made outside, as in aggregation
    riverside.hire("Computer Science", smith);
    riverside.show();

    std::printf("Closing:\n");
    riverside.close();
    riverside.show();
    std::printf("  Still here: %s\n", smith.describe().c_str());

    std::printf("Ordering:\n");
    Order order("ORD-5001");
    order.addItem("Laptop", 1, 99999);
    order.addItem("Mouse", 2, 2999);
    order.addItem("USB Cable", 3, 999);
    order.show();

    std::printf("Cancelling:\n");
    order.cancel();
    order.show();
    return 0;
}
class Professor {
  constructor(
    private readonly name: string,
    private readonly specialization: string,
  ) {}

  getName(): string {
    return this.name;
  }

  describe(): string {
    return `Prof. ${this.name} (${this.specialization})`;
  }
}

// Only a University makes a Department: a part that lives inside one whole
class Department {
  // aggregation: its professors are handed in, never made here
  private readonly professors: Professor[] = [];

  constructor(private readonly name: string) {}

  getName(): string {
    return this.name;
  }

  addProfessor(professor: Professor): void {
    this.professors.push(professor);
    console.log(`  ${professor.getName()} joined ${this.name}`);
  }

  headcount(): number {
    return this.professors.length;
  }

  close(): void {
    this.professors.length = 0; // its professors are let go, not ended
    console.log(`  ${this.name} closed`);
  }
}

class University {
  // composition: the university makes its departments and hands none of them out
  private readonly departments: Department[] = [];

  constructor(private readonly name: string) {}

  openDepartment(deptName: string): void {
    this.departments.push(new Department(deptName));
    console.log(`  ${this.name} opened ${deptName}`);
  }

  hire(departmentName: string, professor: Professor): void {
    for (const dept of this.departments) {
      if (dept.getName() === departmentName) {
        dept.addProfessor(professor);
      }
    }
  }

  show(): void {
    const parts = this.departments
      .map((d) => `${d.getName()} (${d.headcount()})`)
      .join(", ");
    console.log(`  ${this.name}: ${parts || "no departments"}`);
  }

  // Closing the whole ends every part: no department outlives its university
  close(): void {
    const count = this.departments.length;
    for (const dept of this.departments) {
      dept.close();
    }
    this.departments.length = 0;
    console.log(`  ${this.name} closed: ${count} departments went with it`);
  }
}

function money(cents: number): string {
  return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
}

class OrderItem {
  constructor(
    private readonly product: string,
    private readonly quantity: number,
    private readonly unitCents: number,
  ) {}

  describe(): string {
    return `${this.product} x${this.quantity}`;
  }

  subtotal(): number {
    return this.quantity * this.unitCents;
  }
}

class Order {
  // composition: made here, ended here
  private readonly items: OrderItem[] = [];

  constructor(private readonly orderId: string) {}

  addItem(product: string, quantity: number, unitCents: number): void {
    const item = new OrderItem(product, quantity, unitCents);
    this.items.push(item);
    console.log(`  Added ${item.describe()} to ${this.orderId}`);
  }

  total(): number {
    return this.items.reduce((sum, item) => sum + item.subtotal(), 0);
  }

  show(): void {
    const count = this.items.length;
    console.log(`  ${this.orderId}: ${count} items, total ${money(this.total())}`);
  }

  cancel(): void {
    const count = this.items.length;
    this.items.length = 0;
    console.log(`  ${this.orderId} cancelled: ${count} items went with it`);
  }
}

console.log("Founding:");
const riverside = new University("Riverside University");
riverside.openDepartment("Computer Science");
riverside.openDepartment("Mathematics");
riverside.openDepartment("Physics");
const smith = new Professor("Smith", "Algorithms"); // made outside, as in aggregation
riverside.hire("Computer Science", smith);
riverside.show();

console.log("Closing:");
riverside.close();
riverside.show();
console.log(`  Still here: ${smith.describe()}`);

console.log("Ordering:");
const order = new Order("ORD-5001");
order.addItem("Laptop", 1, 99999);
order.addItem("Mouse", 2, 2999);
order.addItem("USB Cable", 3, 999);
order.show();

console.log("Cancelling:");
order.cancel();
order.show();
using System;
using System.Collections.Generic;
using System.Linq;

public class Professor
{
    private readonly string specialization;

    public Professor(string name, string specialization)
    {
        Name = name;
        this.specialization = specialization;
    }

    public string Name { get; }

    public string Describe() => $"Prof. {Name} ({specialization})";
}

// Only a University makes a Department: a part that lives inside one whole
public class Department
{
    // aggregation: its professors are handed in, never made here
    private readonly List<Professor> professors = new();

    internal Department(string name)
    {
        Name = name;
    }

    public string Name { get; }

    public void AddProfessor(Professor professor)
    {
        professors.Add(professor);
        Console.WriteLine($"  {professor.Name} joined {Name}");
    }

    public int Headcount() => professors.Count;

    public void Close()
    {
        professors.Clear(); // its professors are let go, not ended
        Console.WriteLine($"  {Name} closed");
    }
}

public class University
{
    private readonly string name;
    // composition: the university makes its departments and hands none of them out
    private readonly List<Department> departments = new();

    public University(string name)
    {
        this.name = name;
    }

    public void OpenDepartment(string deptName)
    {
        departments.Add(new Department(deptName));
        Console.WriteLine($"  {name} opened {deptName}");
    }

    public void Hire(string departmentName, Professor professor)
    {
        foreach (Department dept in departments)
        {
            if (dept.Name == departmentName)
            {
                dept.AddProfessor(professor);
            }
        }
    }

    public void Show()
    {
        string parts = string.Join(", ",
            departments.Select(d => $"{d.Name} ({d.Headcount()})"));
        Console.WriteLine($"  {name}: {(parts == "" ? "no departments" : parts)}");
    }

    // Closing the whole ends every part: no department outlives its university
    public void Close()
    {
        int count = departments.Count;
        foreach (Department dept in departments)
        {
            dept.Close();
        }
        departments.Clear();
        Console.WriteLine($"  {name} closed: {count} departments went with it");
    }
}

public class OrderItem
{
    private readonly string product;
    private readonly int quantity;
    private readonly int unitCents;

    internal OrderItem(string product, int quantity, int unitCents)
    {
        this.product = product;
        this.quantity = quantity;
        this.unitCents = unitCents;
    }

    public string Describe() => $"{product} x{quantity}";

    public int Subtotal() => quantity * unitCents;
}

public class Order
{
    private readonly string orderId;
    // composition: made here, ended here
    private readonly List<OrderItem> items = new();

    public Order(string orderId)
    {
        this.orderId = orderId;
    }

    public void AddItem(string product, int quantity, int unitCents)
    {
        var item = new OrderItem(product, quantity, unitCents);
        items.Add(item);
        Console.WriteLine($"  Added {item.Describe()} to {orderId}");
    }

    public int Total() => items.Sum(item => item.Subtotal());

    public void Show()
    {
        int count = items.Count;
        Console.WriteLine($"  {orderId}: {count} items, total {Money(Total())}");
    }

    public void Cancel()
    {
        int count = items.Count;
        items.Clear();
        Console.WriteLine($"  {orderId} cancelled: {count} items went with it");
    }

    public static string Money(int cents) => $"{cents / 100}.{cents % 100:D2}";
}

public static class CompositionDemo
{
    public static void Main()
    {
        Console.WriteLine("Founding:");
        var riverside = new University("Riverside University");
        riverside.OpenDepartment("Computer Science");
        riverside.OpenDepartment("Mathematics");
        riverside.OpenDepartment("Physics");
        // made outside, as in aggregation
        var smith = new Professor("Smith", "Algorithms");
        riverside.Hire("Computer Science", smith);
        riverside.Show();

        Console.WriteLine("Closing:");
        riverside.Close();
        riverside.Show();
        Console.WriteLine($"  Still here: {smith.Describe()}");

        Console.WriteLine("Ordering:");
        var order = new Order("ORD-5001");
        order.AddItem("Laptop", 1, 99999);
        order.AddItem("Mouse", 2, 2999);
        order.AddItem("USB Cable", 3, 999);
        order.Show();

        Console.WriteLine("Cancelling:");
        order.Cancel();
        order.Show();
    }
}
package main

import (
	"fmt"
	"strings"
)

type Professor struct {
	name           string
	specialization string
}

func NewProfessor(name, specialization string) *Professor {
	return &Professor{name: name, specialization: specialization}
}

func (p *Professor) Describe() string {
	return fmt.Sprintf("Prof. %s (%s)", p.name, p.specialization)
}

// Only a University makes a Department: a part that lives inside one whole
type Department struct {
	name       string
	professors []*Professor // aggregation: handed in, never made here
}

func (d *Department) AddProfessor(p *Professor) {
	d.professors = append(d.professors, p)
	fmt.Printf("  %s joined %s\n", p.name, d.name)
}

func (d *Department) Headcount() int { return len(d.professors) }

func (d *Department) Close() {
	d.professors = nil // its professors are let go, not ended
	fmt.Printf("  %s closed\n", d.name)
}

type University struct {
	name string
	// composition: the university makes its departments and hands none of them out
	departments []*Department
}

func NewUniversity(name string) *University {
	return &University{name: name}
}

func (u *University) OpenDepartment(deptName string) {
	u.departments = append(u.departments, &Department{name: deptName})
	fmt.Printf("  %s opened %s\n", u.name, deptName)
}

func (u *University) Hire(departmentName string, p *Professor) {
	for _, dept := range u.departments {
		if dept.name == departmentName {
			dept.AddProfessor(p)
		}
	}
}

func (u *University) Show() {
	parts := make([]string, 0, len(u.departments))
	for _, d := range u.departments {
		parts = append(parts, fmt.Sprintf("%s (%d)", d.name, d.Headcount()))
	}
	shown := strings.Join(parts, ", ")
	if shown == "" {
		shown = "no departments"
	}
	fmt.Printf("  %s: %s\n", u.name, shown)
}

// Closing the whole ends every part: no department outlives its university
func (u *University) Close() {
	count := len(u.departments)
	for _, dept := range u.departments {
		dept.Close()
	}
	u.departments = nil
	fmt.Printf("  %s closed: %d departments went with it\n", u.name, count)
}

func Money(cents int) string {
	return fmt.Sprintf("%d.%02d", cents/100, cents%100)
}

type OrderItem struct {
	product   string
	quantity  int
	unitCents int
}

func (i *OrderItem) Describe() string {
	return fmt.Sprintf("%s x%d", i.product, i.quantity)
}

func (i *OrderItem) Subtotal() int { return i.quantity * i.unitCents }

type Order struct {
	orderID string
	items   []*OrderItem // composition: made here, ended here
}

func NewOrder(orderID string) *Order {
	return &Order{orderID: orderID}
}

func (o *Order) AddItem(product string, quantity, unitCents int) {
	item := &OrderItem{product: product, quantity: quantity, unitCents: unitCents}
	o.items = append(o.items, item)
	fmt.Printf("  Added %s to %s\n", item.Describe(), o.orderID)
}

func (o *Order) Total() int {
	sum := 0
	for _, item := range o.items {
		sum += item.Subtotal()
	}
	return sum
}

func (o *Order) Show() {
	count := len(o.items)
	fmt.Printf("  %s: %d items, total %s\n", o.orderID, count, Money(o.Total()))
}

func (o *Order) Cancel() {
	count := len(o.items)
	o.items = nil
	fmt.Printf("  %s cancelled: %d items went with it\n", o.orderID, count)
}

func main() {
	fmt.Println("Founding:")
	riverside := NewUniversity("Riverside University")
	riverside.OpenDepartment("Computer Science")
	riverside.OpenDepartment("Mathematics")
	riverside.OpenDepartment("Physics")
	smith := NewProfessor("Smith", "Algorithms") // made outside, as in aggregation
	riverside.Hire("Computer Science", smith)
	riverside.Show()

	fmt.Println("Closing:")
	riverside.Close()
	riverside.Show()
	fmt.Println("  Still here: " + smith.Describe())

	fmt.Println("Ordering:")
	order := NewOrder("ORD-5001")
	order.AddItem("Laptop", 1, 99999)
	order.AddItem("Mouse", 2, 2999)
	order.AddItem("USB Cable", 3, 999)
	order.Show()

	fmt.Println("Cancelling:")
	order.Cancel()
	order.Show()
}

It prints:

Founding:
  Riverside University opened Computer Science
  Riverside University opened Mathematics
  Riverside University opened Physics
  Smith joined Computer Science
  Riverside University: Computer Science (1), Mathematics (0), Physics (0)
Closing:
  Computer Science closed
  Mathematics closed
  Physics closed
  Riverside University closed: 3 departments went with it
  Riverside University: no departments
  Still here: Prof. Smith (Algorithms)
Ordering:
  Added Laptop x1 to ORD-5001
  Added Mouse x2 to ORD-5001
  Added USB Cable x3 to ORD-5001
  ORD-5001: 3 items, total 1089.94
Cancelling:
  ORD-5001 cancelled: 3 items went with it
  ORD-5001: 0 items, total 0.00

After close, the university has no departments, and nothing else ever held them. A test in Python counted the departments that could still be reached: 3 before close, 0 after. In C++ the list holds the departments themselves, so clearing it destroys them; a test that added a print to the destructor saw it run for each department during close. Smith is still there, because the program made Smith and still holds Smith. The order works the same way: cancelling it ends its three items, and its total goes back to 0.00.

The Code Tell: Who Makes the Part

There is a sign in code that usually tells the two apart: who makes the part. In aggregation, the caller makes the part and hands it in:

smith = Professor("Smith", "Algorithms")  # made outside the department
cs = Department("Computer Science")
cs.add_professor(smith)  # handed in

In composition, the whole makes the part itself:

riverside = University("Riverside University")
riverside.open_department("Computer Science")  # made inside the university

This is a habit, and UML does not require it: "The order and way in which composed objects are created is intentionally not defined." A whole may be handed a part made just for it, as long as nothing else keeps that part. The surer sign is what happens at the end. A whole that aggregates lets its parts go; a whole that composes ends them.

Common Mistakes

Mistake 1: calling every has-a relationship composition. A car has a driver, but the driver was not made for the car and lives on after it is scrapped. That is an association, or an aggregation if the car is treated as a whole holding its passengers. The car's engine, built for that car, is composition.

Mistake 2: composition where parts are shared. A filled diamond from Department to Professor says each professor belongs to one department and ends with it. Professors can hold joint appointments, as Smith does in Aggregation — Has-A with Independent Lifecycle, and they stay when a department closes, so that link is aggregation.

Mistake 3: drawing the filled diamond and not keeping it in code. If an order is deleted and its items stay behind, the design promised something the code does not do. A version of these classes whose create_department returns the new department shows how it slips: a test kept the returned department, shut the university down, and the department still answered, as Computer Science [INACTIVE]. Make the whole end its parts, and hand none of them out. In a database the same promise is a foreign key with ON DELETE CASCADE, which PostgreSQL describes like this: "CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well."

Key Takeaways

  • Composition is a whole that owns its parts: when the whole ends, its parts end with it.
  • A part belongs to one whole at a time. It may be taken out before the end, and then it does not end with the whole.
  • In code the whole makes or receives its parts, hands none of them out, and ends them when it ends. In a database the same promise is ON DELETE CASCADE.
  • Dependency — Objects That Use Each Other comes next: objects that use each other without keeping a reference at all.