Compose or inherit?

Lesson 18 of 19 · Python Object Design

Use inheritance for a genuine behavioral specialization. Use composition when an object needs another object to perform part of its work. A shared function may be enough when no object needs to keep state.

class Uppercase:
    def format(self, text):
        return text.upper()

class InBrackets:
    def format(self, text):
        return "[" + text + "]"

class Sign:
    def __init__(self, formatter):
        self._formatter = formatter

    def display(self, text):
        return self._formatter.format(text)

first = Sign(Uppercase())
second = Sign(InBrackets())
print(first.display("entry"))
print(second.display("entry"))

Output:

ENTRY
[entry]
Sign --has a--> formatter --implements--> format(text) -> string

A sign is not a kind of formatter; it delegates formatting to one. Two independent formatters meet the same contract without inheriting from a common base. Supplying the formatter to the constructor makes the choice explicit. The stored reference could be shared; replacement or mutation rules would need to be part of a larger design’s contract.

Composition is not automatically simpler: collaborators add names and interactions to understand, and an incompatible formatter still fails at runtime. Inheritance shares both behavior and obligations and couples a subclass to base changes. Choose the relationship that reflects the actual promise. If a plain transformation has no state or varying policy, an ordinary function may be the clearest choice.

Chapter contents