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)class Circle {
constructor(radius) {
this.radius = radius;
}
area() {
return Math.PI * this.radius ** 2;
}
}
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
// Works for any object with an area() method, including shapes
// written later. Adding one never means editing this function.
function totalArea(shapes) {
return shapes.reduce((sum, shape) => sum + shape.area(), 0);
}import "math"
type Shape interface {
Area() float64
}
type Circle struct{ Radius float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
type Rectangle struct{ Width, Height float64 }
func (r Rectangle) Area() float64 { return r.Width * r.Height }
// TotalArea works for any Shape, including ones written later.
// Adding one never means editing this function.
func TotalArea(shapes []Shape) float64 {
total := 0.0
for _, s := range shapes {
total += s.Area()
}
return total
}use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
PI * self.radius * self.radius
}
}
struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
// Works for any Shape, including ones written later.
// Adding one never means editing this function.
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}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
- 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.
- Reading S as “one method per class”. The principle is about reasons to change, not size.
- 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?
Every new case modifies working code. Giving each payment method its own class behind a shared interface lets you add one without touching checkout().
Check yourself
A Penguin subclass of Bird throws an error from fly(). Which principle is broken?
Code that expects any Bird to fly breaks when it gets a penguin, so Penguin can’t stand in for its parent type.
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.
Finished this page?
Your list