liveBook · Manning

Composition

As explained in Grokking Data Structures

Composition is a design technique that builds an object from instances of other objects rather than deriving it through inheritance.

Composition builds a class by placing an instance of another class inside it. Instead of inheriting from an array or linked list, the new class owns one and forwards selected operations to it. This supports encapsulation and keeps the public interface focused. section 2.10 section 7.12

Composition is useful when a class needs to reuse an implementation while exposing a smaller, cleaner interface:

  • An UnsortedArray stores a core Array instance internally and manages its own size-related state. section 2.10
  • A Bag wraps a singly linked list and exposes only the operations clients need. section 7.12
  • Forwarding operations keeps methods short: insertion delegates to the linked list, while traversal returns its elements. section 7.12

A class built around another class

A Bag can create a SinglyLinkedList in its constructor, send each inserted value to insert_in_front, and use the list's traversal behavior. Clients work with Bag rather than directly depending on the linked-list implementation. section 7.12

class UnsortedArray:
    def __init__(self, max_size, typecode = 'l'):
        self._array = Array(max_size, typecode)
        self._max_size = max_size
        self._size = 0

The constructor makes composition visible: UnsortedArray stores an Array instance in _array instead of deriving from Array. section 2.10

How Grokking Data Structures covers it

How deep it goes
Defines composition, shows constructors and delegated methods, and stops short of a detailed comparison of composition and inheritance.
Examples
Uses UnsortedArray wrapping Array and Bag delegating insertion and traversal to SinglyLinkedList.
What you can do after
Build it from scratch by wrapping an existing data structure and forwarding only the operations a new class should expose.
How it connects
Connects composition with inheritance, encapsulation, arrays, linked lists, abstract data types, and iterators.

Also explained in

Compare how 11 books explain composition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.