SOLID principles
The five SOLID principles, each with a real violation and its fix in Java and Python, plus DRY, KISS, YAGNI, the Law of Demeter and the cost of over-engineering.
On this page
The problem: every change breaks something far away
A small online shop has grown for two years. Changing the invoice PDF layout broke tax totals last month. Adding a new shipping option meant editing a 400-line method that three people were also editing. The unit tests need a real MySQL database, so nobody runs them. No single decision caused this; hundreds of small ones did.
SOLID is five rules of thumb, collected by Robert C. Martin, that keep classes small and changes local. They are not laws. Each one names a specific kind of pain and the habit that prevents it, and most design patterns turn out to be one of these habits applied to a common problem.
Five rules of thumb, one per letter
- SOLID is five rules of thumb, one per letter. They aren’t laws; they’re the habits that keep classes small and changes local. Let’s meet them one at a time.
| Letter | Principle | One line | The pain it prevents |
|---|---|---|---|
| S | Single responsibility | A class has one reason to change | Unrelated changes colliding in one class |
| O | Open/closed | Add behaviour by adding code, not editing working code | Every new feature re-opening tested code |
| L | Liskov substitution | A subtype must work wherever its parent is expected | Subclasses that crash code written for the parent |
| I | Interface segregation | Don't force clients to depend on methods they don't use | Fat interfaces and fake implementations |
| D | Dependency inversion | Business logic depends on abstractions, not on tools | Logic welded to a database, untestable |
S: single responsibility
A class should have one reason to change, meaning one group of people or one concern that would ask for changes to it. "Does one thing" is a weaker reading; the useful question is "who would ask me to edit this?"
One Invoice class, three reasons to change
- S, single responsibility: a class should have one reason to change. This Invoice adds up totals, prints PDFs and saves to the database. A new PDF layout and a database change both touch it. Split it so each class has one job.
// BEFORE: accounting, the design team and the DBA all edit this class
class Invoice {
long totalCents() { /* sum lines, apply tax */ return 0; }
byte[] toPdf() { /* fonts, layout, logo */ return new byte[0]; }
void save() { /* JDBC, SQL */ }
}
// AFTER: one reason to change each
class Invoice { // business rules
private final List<Long> lineCents;
private final int taxPercent;
Invoice(List<Long> lineCents, int taxPercent) { this.lineCents = List.copyOf(lineCents); this.taxPercent = taxPercent; }
long totalCents() {
long net = lineCents.stream().mapToLong(Long::longValue).sum();
return net + net * taxPercent / 100;
}
}
class InvoicePdfRenderer { byte[] render(Invoice inv) { /* layout only */ return new byte[0]; } }
class InvoiceRepository { void save(Invoice inv) { /* persistence only */ } }# BEFORE: accounting, the design team and the DBA all edit this class
class Invoice:
def total_cents(self): ... # sum lines, apply tax
def to_pdf(self): ... # fonts, layout, logo
def save(self): ... # SQL
# AFTER: one reason to change each
class Invoice: # business rules
def __init__(self, line_cents: list[int], tax_percent: int):
self._lines = tuple(line_cents)
self._tax = tax_percent
def total_cents(self) -> int:
net = sum(self._lines)
return net + net * self._tax // 100
class InvoicePdfRenderer:
def render(self, invoice: Invoice) -> bytes: return b"" # layout only
class InvoiceRepository:
def save(self, invoice: Invoice) -> None: ... # persistence onlyThe benefit: a new PDF layout can't break tax maths, and tax maths can be tested without fonts or a database. The cost: three classes instead of one. That trade is worth it when the concerns really change for different reasons; it is not worth splitting a 20-line class into five.
O: open/closed
Software should be open for extension, closed for modification: you add new behaviour by adding new code (a new class), not by editing code that already works and is tested.
New behaviour as a new class
- O, open/closed: open for extension, closed for modification. Add new behaviour by adding a class, not by editing one that already works. You saw it with shapes and payments.
// BEFORE: every new shipping option edits this method
long shippingCents(String method, int grams) {
switch (method) {
case "standard": return 499;
case "express": return 999 + grams / 100;
default: throw new IllegalArgumentException(method);
}
}
// AFTER: a new option is a new class; nothing existing changes
interface ShippingRule { long cents(int grams); }
class Standard implements ShippingRule { public long cents(int grams) { return 499; } }
class Express implements ShippingRule { public long cents(int grams) { return 999 + grams / 100; } }
class Drone implements ShippingRule { public long cents(int grams) { return grams > 2000 ? 4999 : 1999; } }
class Checkout {
private final ShippingRule shipping;
Checkout(ShippingRule shipping) { this.shipping = shipping; }
long total(long itemsCents, int grams) { return itemsCents + shipping.cents(grams); }
}# BEFORE: every new shipping option edits this function
def shipping_cents(method: str, grams: int) -> int:
if method == "standard":
return 499
if method == "express":
return 999 + grams // 100
raise ValueError(method)
# AFTER: a new option is a new class; nothing existing changes
from typing import Protocol
class ShippingRule(Protocol):
def cents(self, grams: int) -> int: ...
class Standard:
def cents(self, grams): return 499
class Express:
def cents(self, grams): return 999 + grams // 100
class Drone:
def cents(self, grams): return 4999 if grams > 2000 else 1999
class Checkout:
def __init__(self, shipping: ShippingRule):
self.shipping = shipping
def total(self, items_cents: int, grams: int) -> int:
return items_cents + self.shipping.cents(grams)This is the Strategy pattern. Something still maps "drone" to Drone, but that lives in one registry or factory. Open/closed is about the likely axis of change: you cannot be closed against every change, so pick the one the requirements suggest.
L: Liskov substitution
Named after Barbara Liskov: if S is a subtype of T, code written against T must keep working when handed an S, without knowing it got one. A subclass may do more, never less, and never something surprising.
Penguin extends Bird, and fly() throws
- L, Liskov substitution: a subclass must work anywhere its parent is expected. If Penguin extends Bird and fly() throws an error, any code that makes birds fly will crash on penguins. The fix is a better family: not every Bird is a FlyingBird.
Formally, a subtype must not strengthen preconditions (demand more of callers), must not weaken postconditions (promise less), and must preserve invariants. Throwing from an inherited method is the loudest violation; quieter ones are worse. The classic: Square extends Rectangle. A square keeps width and height equal, so setWidth(5) also changes the height, and code that does r.setWidth(5); r.setHeight(4); assert r.area() == 20 fails for squares. Nothing threw; the answer is just wrong.
// BEFORE: Penguin breaks every caller that makes birds fly
class Bird { void fly() { System.out.println("flap"); } }
class Penguin extends Bird {
@Override void fly() { throw new UnsupportedOperationException("penguins can't fly"); }
}
// AFTER: only things that fly promise to fly
abstract class Bird { abstract String eat(); }
interface Flying { void fly(); }
class Sparrow extends Bird implements Flying {
String eat() { return "seeds"; }
public void fly() { System.out.println("flap"); }
}
class Penguin extends Bird {
String eat() { return "fish"; }
void swim() { System.out.println("dive"); }
}
void migrate(List<? extends Flying> flock) { flock.forEach(Flying::fly); } // penguins can't get in# BEFORE: Penguin breaks every caller that makes birds fly
class Bird:
def fly(self): print("flap")
class Penguin(Bird):
def fly(self): raise NotImplementedError("penguins can't fly")
# AFTER: only things that fly promise to fly
from abc import ABC, abstractmethod
from typing import Protocol
class Bird(ABC):
@abstractmethod
def eat(self) -> str: ...
class Flying(Protocol):
def fly(self) -> None: ...
class Sparrow(Bird):
def eat(self): return "seeds"
def fly(self): print("flap")
class Penguin(Bird):
def eat(self): return "fish"
def swim(self): print("dive")
def migrate(flock: list[Flying]) -> None: # a type checker rejects penguins here
for bird in flock:
bird.fly()The fix is a better family: not every Bird is a Flying thing. If you catch yourself writing if (bird instanceof Penguin) before calling fly(), Liskov is already broken.
I: interface segregation
Clients should not be forced to depend on methods they do not use. A fat interface makes every implementer fake the methods it can't support, and every caller depend on changes to methods it never calls.
A fat Machine interface versus small ones
- I, interface segregation: don’t force a class to depend on methods it doesn’t use. A fat Machine interface makes a simple printer pretend to scan and fax. Several small interfaces fit better.
// BEFORE: a simple printer must pretend to scan and fax
interface Machine { void print(String doc); void scan(String doc); void fax(String doc); }
class BasicPrinter implements Machine {
public void print(String doc) { System.out.println("printing " + doc); }
public void scan(String doc) { throw new UnsupportedOperationException(); } // also an LSP smell
public void fax(String doc) { throw new UnsupportedOperationException(); }
}
// AFTER: small role interfaces; implement only what you can do
interface Printer { void print(String doc); }
interface Scanner { void scan(String doc); }
interface Fax { void fax(String doc); }
class SimplePrinter implements Printer {
public void print(String doc) { System.out.println("printing " + doc); }
}
class OfficeMachine implements Printer, Scanner, Fax {
public void print(String doc) { System.out.println("printing " + doc); }
public void scan(String doc) { System.out.println("scanning " + doc); }
public void fax(String doc) { System.out.println("faxing " + doc); }
}
class PayslipJob { // depends only on what it uses
private final Printer printer;
PayslipJob(Printer printer) { this.printer = printer; }
void run() { printer.print("payslips.pdf"); }
}# AFTER (Python): small protocols; a class satisfies the ones whose methods it has
from typing import Protocol
class Printer(Protocol):
def print_doc(self, doc: str) -> None: ...
class Scanner(Protocol):
def scan(self, doc: str) -> None: ...
class SimplePrinter:
def print_doc(self, doc): print(f"printing {doc}")
class OfficeMachine:
def print_doc(self, doc): print(f"printing {doc}")
def scan(self, doc): print(f"scanning {doc}")
class PayslipJob: # depends only on what it uses
def __init__(self, printer: Printer):
self.printer = printer
def run(self):
self.printer.print_doc("payslips.pdf")
PayslipJob(SimplePrinter()).run()
PayslipJob(OfficeMachine()).run()Interface segregation and Liskov often show up together: a fat interface forces implementers into throwing stubs, which then break substitution.
D: dependency inversion
High-level policy should not depend on low-level details; both should depend on abstractions. The business rule "place an order" should not know whether orders go to MySQL, DynamoDB or a test list. The service owns an interface describing what it needs; the database adapter implements it and is plugged in from outside.
OrderService depends on an interface; MySQL is plugged in
- D, dependency inversion: important code should depend on an abstraction, not on a specific tool. OrderService talks to a Database interface; MySQL is plugged in from outside, and tests plug in a fast in-memory fake.
import java.util.*;
// BEFORE: the service builds its own database client, so tests need a real database
// class OrderService { private final MySqlClient db = new MySqlClient("prod-host"); ... }
// AFTER
record Order(String id, long totalCents) { }
interface OrderRepository { // owned by the business layer
void save(Order order);
Optional<Order> find(String id);
}
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; } // injected: dependency injection
Order place(String id, long totalCents) {
if (totalCents <= 0) throw new IllegalArgumentException("empty order");
Order o = new Order(id, totalCents);
repo.save(o);
return o;
}
}
class InMemoryOrderRepository implements OrderRepository { // for tests and demos
private final Map<String, Order> rows = new HashMap<>();
public void save(Order o) { rows.put(o.id(), o); }
public Optional<Order> find(String id) { return Optional.ofNullable(rows.get(id)); }
}
// class MySqlOrderRepository implements OrderRepository { ... JDBC here ... }
public class Main {
public static void main(String[] args) {
OrderRepository repo = new InMemoryOrderRepository();
OrderService service = new OrderService(repo);
service.place("o-1", 2_500);
System.out.println(repo.find("o-1").isPresent()); // true, and no database needed
}
}from dataclasses import dataclass
from typing import Optional, Protocol
@dataclass(frozen=True)
class Order:
id: str
total_cents: int
class OrderRepository(Protocol): # owned by the business layer
def save(self, order: Order) -> None: ...
def find(self, order_id: str) -> Optional[Order]: ...
class OrderService:
def __init__(self, repo: OrderRepository): # injected: dependency injection
self._repo = repo
def place(self, order_id: str, total_cents: int) -> Order:
if total_cents <= 0:
raise ValueError("empty order")
order = Order(order_id, total_cents)
self._repo.save(order)
return order
class InMemoryOrderRepository: # for tests and demos
def __init__(self):
self._rows: dict[str, Order] = {}
def save(self, order: Order) -> None:
self._rows[order.id] = order
def find(self, order_id: str) -> Optional[Order]:
return self._rows.get(order_id)
if __name__ == "__main__":
repo = InMemoryOrderRepository()
OrderService(repo).place("o-1", 2_500)
print(repo.find("o-1") is not None) # True, and no database neededTwo terms people mix up: dependency inversion is the design principle (depend on an abstraction the high-level code owns); dependency injection is the technique of passing dependencies in (usually through the constructor) instead of creating them inside. Spring, Guice and Dagger are DI containers that do the wiring for you; plain constructor parameters, as above, are DI too.
Beyond SOLID: four more you will be asked about
| Principle | Says | Example | The trap |
|---|---|---|---|
| DRY (don't repeat yourself) | Every piece of knowledge has one home | The tax rate lives in one constant, not in five methods | Merging code that only looks alike: two rules that change for different reasons get welded together. Duplication is cheaper than the wrong abstraction. |
| KISS (keep it simple) | Prefer the simplest design that works | A HashMap cache before a pluggable cache framework | Simple is not the same as easy to write once; it means easy to read and change. |
| YAGNI (you aren't gonna need it) | Don't build for requirements you don't have | No plugin system for one shipping rule | It is not "never design ahead": cheap, likely, hard-to-retrofit things (IDs, money types, time zones) are worth doing early. |
| Law of Demeter (least knowledge) | Talk to your direct collaborators, not their insides | order.shippingCity() instead of order.getCustomer().getAddress().getCity() | It is about reaching through objects, not counting dots: stream().filter().map() and builders are fine. |
The Demeter example is worth seeing: the long chain couples the caller to the shape of Order, Customer and Address at once, so restructuring any of them breaks it. Letting Order answer the question keeps that knowledge in one place (which is also encapsulation: tell, don't ask).
SOLID is a tool for pain you can feel
- A warning: SOLID is a tool for pain you can feel. A tiny script doesn’t need five interfaces. Apply these rules where change keeps hurting, and you’ll find most design patterns are just SOLID applied to a common problem.
When not to bother
- Scripts, prototypes and one-off jobs that will be thrown away.
- Stable, small code that has not changed in a year: refactoring it for SOLID adds risk for no gain.
- When the abstraction would be the only one of its kind and tests don't need a fake: wait for the second case (the "rule of three": refactor on the third repetition).
In the interview
Name every SOLID problem in this class and sketch the fix in Java and Python.
class ReportService {
public void monthlyReport(String type) {
List<Sale> sales = new MySqlSalesDao().findLastMonth(); // (a)
String out;
if (type.equals("csv")) out = toCsv(sales); // (b)
else if (type.equals("html")) out = toHtml(sales);
else throw new IllegalArgumentException(type);
new SmtpMailer("smtp.corp").send("ceo@corp.example", out); // (c)
}
}Compare with our answer
(a) and (c): the service creates its database and mail clients, so it depends on details and can't be tested without them (D). (b): every new format edits this method (O). Overall, fetching, formatting and sending are three reasons to change in one class (S).
interface SalesSource { List<Sale> lastMonth(); }
interface ReportFormat { String render(List<Sale> sales); }
interface Mailer { void send(String to, String body); }
class ReportService {
private final SalesSource sales;
private final Mailer mailer;
ReportService(SalesSource sales, Mailer mailer) { this.sales = sales; this.mailer = mailer; }
void monthlyReport(ReportFormat format, String recipient) {
mailer.send(recipient, format.render(sales.lastMonth()));
}
}from typing import Protocol
class SalesSource(Protocol):
def last_month(self) -> list: ...
class ReportFormat(Protocol):
def render(self, sales: list) -> str: ...
class Mailer(Protocol):
def send(self, to: str, body: str) -> None: ...
class ReportService:
def __init__(self, sales: SalesSource, mailer: Mailer):
self.sales, self.mailer = sales, mailer
def monthly_report(self, fmt: ReportFormat, recipient: str) -> None:
self.mailer.send(recipient, fmt.render(self.sales.last_month()))A strong answer mentions: dependency inversion for the DAO and the mailer, injected through the constructor · open/closed for the formats, one class each · single responsibility (fetch, format, send) · the hard-coded recipient moved to a parameter or configuration · tests using fakes for the source and mailer.
The shop's OrderService sends an SMS on every order through new TwilioClient(...) inside place(). Now: orders must also go out by WhatsApp for some customers, and the CI pipeline must never send real messages. What changes, and where?
Compare with our answer
Introduce a Notifier interface owned by the order code, inject a list of notifiers (or a composite) into OrderService, and implement SmsNotifier and WhatsAppNotifier as adapters around the vendor clients. Tests inject a RecordingNotifier that stores messages in a list.
interface Notifier { void orderPlaced(Order order); }
class OrderService {
private final OrderRepository repo;
private final List<Notifier> notifiers;
OrderService(OrderRepository repo, List<Notifier> notifiers) {
this.repo = repo; this.notifiers = List.copyOf(notifiers);
}
Order place(String id, long totalCents) {
Order o = new Order(id, totalCents);
repo.save(o);
notifiers.forEach(n -> n.orderPlaced(o));
return o;
}
}
class RecordingNotifier implements Notifier { // used in tests
final List<Order> seen = new ArrayList<>();
public void orderPlaced(Order order) { seen.add(order); }
}from typing import Protocol
class Notifier(Protocol):
def order_placed(self, order) -> None: ...
class OrderService:
def __init__(self, repo, notifiers: list[Notifier]):
self._repo, self._notifiers = repo, list(notifiers)
def place(self, order_id: str, total_cents: int):
order = Order(order_id, total_cents)
self._repo.save(order)
for n in self._notifiers:
n.order_placed(order)
return order
class RecordingNotifier: # used in tests
def __init__(self):
self.seen = []
def order_placed(self, order):
self.seen.append(order)A strong answer mentions: a Notifier interface owned by the business code (DIP) · one adapter class per vendor (OCP) · constructor injection of the list · a fake notifier in tests · deciding per customer which channels apply (a preference lookup, not an if/else in place) · that a failing notification should not roll back a saved order (send asynchronously or via an outbox).
- S: one reason to change per class; ask "who would ask me to edit this?"
- O: extend by adding classes; keep the choice in one factory or registry (Strategy, Decorator).
- L: subtypes keep the parent's contract: no stronger preconditions, no weaker postconditions, no throwing stubs (Penguin, Square).
- I: small role interfaces; nobody implements or depends on methods they don't use.
- D: business code owns interfaces; tools implement them; inject through constructors. DIP is the principle, DI the technique.
- DRY = one home per piece of knowledge, not "merge similar-looking code". KISS, YAGNI: simplest thing; nothing speculative.
- Law of Demeter: ask your neighbour, don't reach through it (
order.shippingCity()). - Over-engineering is a failure too: add an abstraction when change hurts or the requirements name the variation.
1. A UserService validates sign-ups, hashes passwords, sends welcome emails and writes audit logs. The email team's template change caused a regression in password hashing. Which principle was violated most directly?
The root problem is unrelated concerns sharing a class, so a change for one reason broke another. Open/closed is also involved, but it is a symptom of the missing split.
2. Square extends Rectangle; setWidth on a square also sets the height. A test does r.setWidth(5); r.setHeight(4); and expects area 20. Which principle does this break?
Code written for rectangles silently gets the wrong answer when handed a square. That is a substitution failure even though nothing throws.
3. A Worker interface has work() and eat(). A RobotWorker implements eat() as an empty method. What is the best fix?
Clients and implementers should not depend on methods they don't use. A throwing default just moves the failure to run time, and inheriting from HumanWorker adds a false "is a".
4. What is the difference between dependency inversion and dependency injection?
DIP says what to depend on; DI is one technique for supplying the implementation. You can inject a concrete class (DI without DIP).
5. A colleague merges two near-identical 15-line validation functions, one for invoices and one for shipping labels, into one with five flags. Six months later each change to one breaks the other. What went wrong?
DRY is about one home per piece of knowledge. Coincidentally similar code is not shared knowledge, and merging it couples unrelated rules. Duplication is cheaper than the wrong abstraction.
6. Which line breaks the Law of Demeter in a way worth fixing?
The chain reaches through three other objects' internals, coupling the caller to all of them. Streams, builders and value arithmetic return objects meant for chaining.
7. You're designing a small URL shortener in a 45-minute round. Which is the best use of SOLID?
Abstractions should follow likely change and testing needs. Interfaces everywhere is over-engineering, none at all makes testing and extension harder, and one class per method misreads single responsibility.
Score 60% or more and the lesson is marked complete.