SOLID Principles
The five SOLID principles with before-and-after code — single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion — plus when not to apply them.
SOLID is five principles (collected by Robert C. Martin) for object-oriented code that's easy to change. They are heuristics, not laws: each one reduces a specific kind of pain. Learn the pain, and you'll know when to apply them.
| Letter | Principle | In one line |
|---|---|---|
| S | Single Responsibility | A class should have one reason to change |
| O | Open/Closed | Open for extension, closed for modification |
| L | Liskov Substitution | Subtypes must be usable wherever the base type is |
| I | Interface Segregation | Don't force clients to depend on methods they don't use |
| D | Dependency Inversion | Depend on abstractions, not concrete details |
S — Single Responsibility
"One reason to change" means one actor or concern that might ask for changes. A class that calculates pay, formats reports and saves to the database changes when accounting, the report designers or the DBAs want something.
class Invoice {
long total() {...}
String toPdf() {...} // presentation
void saveToDb() {...} // persistence
void emailCustomer() {...} // notification
}class Invoice { long total() {...} }
class InvoicePdfRenderer { byte[] render(Invoice i) {...} }
class InvoiceRepository { void save(Invoice i) {...} }
class InvoiceMailer { void send(Invoice i) {...} }O — Open/Closed
You should be able to add behaviour without editing existing, tested code. The typical smell is a switch on type that grows with every new case.
// Before: every new shipping method edits this function
double cost(Order o) {
switch (o.shipping()) {
case "standard": return 5;
case "express": return 15;
default: throw new IllegalArgumentException();
}
}
// After: add a class, touch nothing else
interface ShippingPolicy { double cost(Order o); }
class Standard implements ShippingPolicy { public double cost(Order o) { return 5; } }
class Express implements ShippingPolicy { public double cost(Order o) { return 15; } }
class Drone implements ShippingPolicy { public double cost(Order o) { return 25; } } // newfrom typing import Protocol
class ShippingPolicy(Protocol):
def cost(self, order) -> float: ...
class Standard:
def cost(self, order): return 5
class Express:
def cost(self, order): return 15
class Drone: # new behaviour, no edits elsewhere
def cost(self, order): return 25
def checkout(order, policy: ShippingPolicy):
return order.subtotal + policy.cost(order)interface ShippingPolicy { cost(o: Order): number; }
const standard: ShippingPolicy = { cost: () => 5 };
const express: ShippingPolicy = { cost: () => 15 };
const drone: ShippingPolicy = { cost: () => 25 }; // new
function checkout(o: Order, policy: ShippingPolicy) {
return o.subtotal + policy.cost(o);
}This is the Strategy pattern. Don't pre-abstract everything, though: apply OCP where change is actually happening.
L — Liskov Substitution
If S is a subtype of T, code written for T must work correctly with an S. Subtypes must honour the parent's contract: they may not strengthen preconditions, weaken postconditions, or throw surprising exceptions.
The classic violation: Square extends Rectangle.
class Rectangle {
protected int w, h;
void setWidth(int w) { this.w = w; }
void setHeight(int h) { this.h = h; }
int area() { return w * h; }
}
class Square extends Rectangle {
@Override void setWidth(int w) { this.w = w; this.h = w; } // keeps it square...
@Override void setHeight(int h) { this.w = h; this.h = h; }
}
void stretch(Rectangle r) {
r.setWidth(5); r.setHeight(4);
assert r.area() == 20; // fails for Square: area is 16
}Mathematically a square is a rectangle, but a mutable Square doesn't behave like a mutable Rectangle. Fixes: make shapes immutable, or don't relate them by inheritance. Other LSP smells: overriding a method to throw UnsupportedOperationException, or instanceof checks in callers.
I — Interface Segregation
Many small, focused interfaces beat one fat one. Clients shouldn't have to implement or depend on methods they don't need.
interface Machine {
void print(Doc d);
void scan(Doc d);
void fax(Doc d);
}
class BasicPrinter implements Machine {
public void scan(Doc d) {
throw new UnsupportedOperationException();
}
...
}interface Printer { void print(Doc d); }
interface Scanner { void scan(Doc d); }
interface Fax { void fax(Doc d); }
class BasicPrinter implements Printer {...}
class OfficeMachine
implements Printer, Scanner, Fax {...}D — Dependency Inversion
High-level policy (business rules) shouldn't depend on low-level details (databases, HTTP clients). Both should depend on abstractions, and the abstraction is owned by the high-level side.
interface OrderRepository { void save(Order o); Optional<Order> find(String id); }
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; } // injected
void place(Order o) { /* rules */ repo.save(o); }
}
// Production
new OrderService(new PostgresOrderRepository(dataSource));
// Tests
new OrderService(new InMemoryOrderRepository());class OrderRepository(Protocol):
def save(self, order: Order) -> None: ...
def find(self, order_id: str) -> Order | None: ...
class OrderService:
def __init__(self, repo: OrderRepository):
self.repo = repo
def place(self, order: Order):
... # business rules
self.repo.save(order)
service = OrderService(PostgresOrderRepository(pool)) # production
test_service = OrderService(InMemoryOrderRepository()) # testsinterface OrderRepository {
save(o: Order): Promise<void>;
find(id: string): Promise<Order | undefined>;
}
class OrderService {
constructor(private repo: OrderRepository) {}
async place(o: Order) { /* rules */ await this.repo.save(o); }
}
const service = new OrderService(new PostgresOrderRepository(pool));
const testService = new OrderService(new InMemoryOrderRepository());Dependency inversion is the principle; dependency injection is the technique of passing dependencies in (Dependency injection).
When SOLID goes wrong
- SRP: separate concerns that change for different reasons.
- OCP: add behaviour by adding code (polymorphism), not by editing switches.
- LSP: subtypes must honour the base contract — Square/Rectangle is the classic violation.
- ISP: small, role-specific interfaces.
- DIP: business logic depends on interfaces it owns; details implement them; inject dependencies.
QExplain the Liskov Substitution Principle with an example.medium
Any code expecting a base type must work correctly with a subtype. A mutable Square extending Rectangle violates it: code that sets width 5 and height 4 expects area 20, but the square forces both sides equal and returns 16. The subtype changed the parent's behaviour contract, so it isn't a valid substitute.
QWhat is the difference between dependency inversion and dependency injection?medium
Dependency inversion is a design principle: high-level modules depend on abstractions rather than concrete low-level modules. Dependency injection is a technique for supplying those dependencies from outside (constructor, setter, container) instead of creating them internally. DI is a common way to achieve DIP.