liveBook · Manning

HAS-A relationship

As explained in Software Design for Python Programmers

Aggregation is a UML whole-part relationship in which a container object refers to contained objects that can exist independently of the container.

Aggregation is a UML whole-part relationship in which a container refers to contained objects that can exist independently. The container uses an open diamond at the relationship tail. section 4.3.2

Use aggregation when:

  • A Catalogue contains zero or more Book objects, while each Book can exist outside the Catalogue. section 4.3.2
  • A class should control access to another object without exposing invalid operations. section 7.2
  • Aggregation better expresses a has-a relationship than inheritance when substitution would permit inappropriate operations. section 7.2 section 7.3

Refactoring CircularBuffer

A CircularBuffer implemented as a list exposes indexing and pop(), allowing callers to corrupt its invariants. Refactoring it as a standalone class that aggregates a private list permits only add() and remove(), preventing the demonstrated crash. section 7.2

Figure 4.8 Class Catalogue aggregates class Book. Each Catalogue object contains zero or more Book objects in a list instance variable named booklist. The open diamond at the tail of the dependency arrow is next to the diagram for the container class Catalogue.
A black text on a white background

Description automatically generated

Shows the open-diamond notation and the Catalogue-to-Book relationship, including the container's list of contained objects. section 4.3.2

How Software Design for Python Programmers covers it

How deep it goes
Explains UML notation, independent lifetimes, composition contrast, and a complete encapsulation refactoring with failing and corrected programs.
Examples
Uses Catalogue–Book containment, Bookshelf–Book relationships, and a CircularBuffer that encapsulates a list.
What it assumes
Assumes basic classes, instance variables, inheritance, UML relationships, and the distinction between is-a and has-a.
What you can do after
Apply it via UML diagrams and encapsulated classes when choosing between inheritance and containment.
How it connects
Connects aggregation with composition, inheritance, the Liskov Substitution Principle, and UML class diagrams.

Also explained in

Compare how 2 books explain HAS-A relationship →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.