Course contentsShow
← Python
Lesson 445 of 1,0607. Object-Oriented ProgrammingFree lesson

Designing Flexible Object Hierarchies

You will refactor code to use inheritance and polymorphism to reduce redundancy and improve the extensibility of your class systems.

In this lesson, you will learn how to design flexible object hierarchies by balancing inheritance and composition to create systems that are easy to extend without constant refactoring.

The Problem of Rigid Hierarchies

When designing classes, it is tempting to create deep, rigid inheritance chains like Animal -> Mammal -> Dog. While this feels logical, it quickly becomes brittle. If you suddenly need a RobotDog that shares behaviors with Dog but isn't an Animal, your hierarchy falls apart. Designing for flexibility means favoring shallow hierarchies and ensuring that subclasses only inherit what they truly are, rather than what they do.

Strategy: Favor Composition Over Inheritance

To keep your hierarchies flexible, identify behaviors that can be "plugged in" rather than baked into the base class. Instead of forcing every class to inherit from a long chain of ancestors, you can use Mixin Classes or Abstract Base Classes to define specific capabilities.

Consider this example where we need to process different types of documents:

from abc import ABC, abstractmethod

class Document(ABC):
    @abstractmethod
    def display(self):
        pass

class PDFDocument(Document):
    def display(self):
        print("Rendering PDF layers.")

class TextDocument(Document):
    def display(self):
        print("Displaying raw text.")

By inheriting from a common Document interface, we can treat any document type interchangeably. If we later want to add a CloudStorageMixin to specific documents, we can simply add it to the class definition without modifying the base Document class:

class CloudDocument(PDFDocument, CloudStorageMixin):
    pass

Designing for Change

A flexible hierarchy allows you to swap or add features by composing smaller, specialized classes rather than creating "God objects" that inherit everything. By keeping your base classes focused on the "is-a" relationship and using mixins or interfaces for "can-do" behaviors, your system remains decoupled. When you need to add a new feature, you simply add a new class to the mix rather than rewriting your existing inheritance tree.

Key Takeaway: Design flexible hierarchies by keeping inheritance chains shallow and using interfaces and mixins to compose behavior, ensuring your code remains modular and easy to extend.