Skip to the workspace
Pebellslearn by building
Design Principles  ›  Capstone Project

SOLID, Part 2 — Liskov, Interface Segregation and Dependency Inversion

SOLID 18 minSubtypes must keep their parent's promises, interfaces should be small and client-shaped, and high-level policy should depend on abstractions rather than on concrete details.

software design architecture / SOLID, Part 2 — Liskov, Interface Segregation and Dependency Inversion

Explore each scene at your own pace.

01 · The rule

The rule

SOLID, Part 2 — Liskov, Interface Segregation and Dependency Inversion

Shelfwise's dispatch job loops over every product in paid orders and calls product.ship(). The night the first e-book sold, the job crashed: EBook.ship() raised NotImplementedError. The last three SOLID letters explain why that happened and how to design so it cannot.

The rule

Keep the parent's promises, keep interfaces small, and depend on abstractions.

L — Liskov Substitution Principle (LSP). Anywhere code uses a parent type, any subtype must work without surprises. A subclass may do its job differently, but it may not refuse the job, demand more from callers, or give back less than the parent promised. EBook.ship() raising an error breaks every caller that trusted Product.ship().

I — Interface Segregation Principle (ISP). No class should be forced to depend on methods it does not use. The e-book crash has a root cause: Product promised ship() and download_link() to everyone. Split the fat interface:

class Product(ABC):
    @abstractmethod
    def price(self): ...

class Shippable(ABC):
    @abstractmethod
    def ship(self, address): ...

class Downloadable(ABC):
    @abstractmethod
    def download_link(self): ...

class Book(Product, Shippable): ...
class EBook(Product, Downloadable): ...

The dispatch job now asks for Shippable things only, and an e-book is never handed to it.

D — Dependency Inversion Principle (DIP). High-level policy (checkout rules) should not depend on low-level details (one payment provider's client). Both should depend on an abstraction.

class Checkout:
    def __init__(self, gateway: PaymentGateway):   # any gateway
        self.gateway = gateway

Before, Checkout created AcmePayClient() inside itself, so changing provider meant editing checkout. Now the detail plugs into an abstraction that checkout owns, and a test can pass in a FakeGateway. Passing the dependency in like this is called dependency injection.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.