programmingconcepts

§ 7.1 · Design

SOLID

Five principles for object-oriented code that stays easy to change: small parts, extended without editing, depending on abstractions.

SOLID is a set of five object-oriented design principles: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion. Robert C. Martin collected them around 2000, and Michael Feathers coined the acronym. Each aims to keep code easy to change, so a new feature means adding code rather than rewriting what already works.

S
Single responsibility
O
Open/closed
L
Liskov substitution
I
Interface segregation
D
Dependency inversion
Requires
Objects and classes

Why it exists

Code that works today has to change tomorrow. The pain usually comes from coupling: one edit forces edits in five other places, or a class can’t be tested without a database. Each SOLID principle names one way to cut that coupling.

S: Single responsibility

A unit should have one reason to change. If a Report class computes totals, formats HTML and emails the result, then a new email provider, a design change and a tax rule all edit the same file. Split it into a calculator, a formatter and a sender, and each change lands in one place.

“One reason” means one source of change, like one team or one concern, not one method.

O: Open/closed

Open for extension, closed for modification. You should be able to add behaviour without editing code that already works and is already tested.

The example below shows it. total_area asks each shape for its own area, so adding a triangle means writing a new class. Nothing in total_area changes. The alternative, a function with if shape.kind == "circle" ... elif ..., has to be edited, and retested, for every new shape.

import math


class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2


class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height


def total_area(shapes):
    # Works for any object with an area() method, including shapes
    # written later. Adding one never means editing this function.
    return sum(shape.area() for shape in shapes)

L: Liskov substitution

A subtype must work anywhere its parent type is expected. Code that takes a Shape shouldn’t need to check which shape it got.

The classic violation: a Square that inherits from Rectangle and keeps its sides equal. A caller that sets the width to 2 and the height to 5 expects an area of 10, but the square gives 25. Square is a rectangle in geometry, but not in behaviour, so it shouldn’t be a subtype here.

I: Interface segregation

Don’t force clients to depend on methods they don’t use. A Printer interface with print, scan and fax makes a simple printer stub out two methods with “not supported” errors. Split it into Printer, Scanner and Fax, and each device takes only what it does.

Go and Rust push this naturally: their interfaces and traits tend to have one or two methods, like Go’s io.Reader.

D: Dependency inversion

Depend on abstractions, not concrete details. High-level logic, like “greet the user”, shouldn’t create its own low-level parts, like the system clock or a database. It should receive something that fits an interface, so the real part can be swapped for a fake in tests or a different one in production.

The usual way to apply it is dependency injection.

Common mistakes

  1. Splitting too early. An interface with one implementation and no tests that need a fake is extra code for no gain. Wait for the second case.
  2. Reading S as “one method per class”. The principle is about reasons to change, not size.
  3. Inheriting for reuse. Inheriting just to borrow code often breaks Liskov substitution. Composition, holding the other object as a field, is usually safer.

Check yourself

Check yourself

Adding a new payment method means editing a long if/else chain in checkout(). Which principle does that break?

Check yourself

A Penguin subclass of Bird throws an error from fly(). Which principle is broken?

Sources

  • Robert C. Martin, “Design Principles and Design Patterns” (2000).
  • Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices (2002).
  • Barbara Liskov and Jeannette Wing, “A behavioral notion of subtyping,” ACM Transactions on Programming Languages and Systems 16, no. 6 (1994): 1811–1841.
  • Bertrand Meyer, Object-Oriented Software Construction (1988), the source of the open/closed principle.

Newsletter

One new concept each week, by email.

Signup opens soon.