What are SOLID Design Principles
SOLID is five rules that all push toward one mechanism: isolate each independent reason your code might change behind its own abstraction, so a future change touches exactly one place instead of rippling through call sites you forgot existed. The acronym (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion) is just five angles on that single goal — they overlap heavily, and a design that violates one usually violates the next.
Below is the one-line core of each, then a single worked example where a naive class violates SRP, OCP, and DIP at once, and we fix all three by introducing one abstraction.
| Letter | Name | The rule in one line | The smell when you break it |
|---|---|---|---|
| S | Single Responsibility | A class should have one reason to change — one actor it answers to. | Editing tax logic forces you to re-test the PDF renderer in the same class. |
| O | Open/Closed | Add new behavior by adding code, not by editing tested code. | Every new payment type means another branch in one growing if/else. |
| L | Liskov Substitution | Any subtype must be usable wherever the base type is, with no surprises. | Square extends Rectangle breaks code that sets width and height independently. |
| I | Interface Segregation | Don't force a client to depend on methods it never calls. | A read-only consumer must stub out write() to compile. |
| D | Dependency Inversion | High-level policy and low-level detail both depend on an abstraction. | Your order logic news a concrete MySQLDatabase, so it can't be unit-tested. |
One worked example: the same class, before and after
A billing service computes an invoice total, applies a discount, persists it, and emails the customer. Here is the naive version — it does everything itself.
// BEFORE — violates SRP, OCP, and DIP at once
class InvoiceService {
double total(Order order) {
double sum = 0;
for (Item i : order.items()) sum += i.price() * i.qty();
// discount logic baked in with a type switch (OCP violation)
if (order.customerType().equals("REGULAR")) sum *= 1.0;
else if (order.customerType().equals("PREMIUM")) sum *= 0.90;
else if (order.customerType().equals("EMPLOYEE")) sum *= 0.75;
// persistence: hard dependency on a concrete class (DIP violation)
new MySQLDatabase().save(order.id(), sum);
// emailing: a third reason to change lives here too (SRP violation)
new SmtpMailer().send(order.email(), "You owe " + sum);
return sum;
}
}Three different teams can force an edit to this one method: the pricing team (new discount tier), the infra team (move off MySQL), and the comms team (switch to a queue instead of SMTP). That is three reasons to change in one place — the root SOLID failure.
The fix introduces abstractions so each reason to change lives behind its own seam. Discounts become a strategy (OCP), storage and mail become interfaces the service depends on (DIP), and the service keeps only the orchestration responsibility (SRP).
// AFTER
interface DiscountPolicy { double factor(); } // OCP seam
class RegularDiscount implements DiscountPolicy { public double factor(){ return 1.00; } }
class PremiumDiscount implements DiscountPolicy { public double factor(){ return 0.90; } }
class EmployeeDiscount implements DiscountPolicy { public double factor(){ return 0.75; } }
interface InvoiceStore { void save(String id, double amount); } // DIP seam
interface Notifier { void notify(String to, String msg); } // DIP seam
class InvoiceService {
private final InvoiceStore store;
private final Notifier notifier;
InvoiceService(InvoiceStore store, Notifier notifier) { // injected, not new'd
this.store = store; this.notifier = notifier;
}
double total(Order order, DiscountPolicy discount) {
double sum = 0;
for (Item i : order.items()) sum += i.price() * i.qty();
sum *= discount.factor();
store.save(order.id(), sum);
notifier.notify(order.email(), "You owe " + sum);
return sum;
}
}Why the naive version is wrong: a new STUDENT tier means editing and re-testing a method that also does I/O and email; in the fixed version it means writing one new StudentDiscount class and changing nothing tested. And because store and notifier are interfaces, a unit test passes fakes and never touches a real database or SMTP server.
Trace it with real values
A PREMIUM order: 2 widgets at $30 and 1 cable at $20. Follow the fixed total() step by step.
| Step | Operation | Running value |
|---|---|---|
| 1 | 2 × $30 (widgets) | sum = 60.00 |
| 2 | + 1 × $20 (cable) | sum = 80.00 |
| 3 | × PremiumDiscount.factor() = 0.90 | sum = 72.00 |
| 4 | store.save("ORD-7", 72.00) | persisted via injected store |
| 5 | notifier.notify(...) → "You owe 72.0" | returns 72.00 |
Swap in EmployeeDiscount (0.75) and only step 3 changes: 80.00 × 0.75 = 60.00. No edit to InvoiceService — that is OCP working.
Pitfalls
- Treating each letter as a separate checklist. They are facets of one idea. The example above fixed SRP, OCP, and DIP with a single move — introducing abstractions at the change boundaries. If you find yourself "applying DIP" with no reason-to-change in mind, you're cargo-culting.
- Over-abstracting on day one (the real cost). Wrapping every class in an interface "to be SOLID" produces a maze of one-implementation interfaces, indirection that obscures control flow, and harder debugging. An interface with exactly one implementation forever is a liability, not a principle.
- SRP misread as "one method per class." SRP is about one reason to change (one actor/stakeholder), not one operation. A class can have ten methods and still serve a single responsibility.
- The subtle Liskov trap. LSP violations compile fine and pass the obvious tests.
Square extends Rectanglelooks correct until a caller doessetWidth(5); setHeight(4); assert area == 20and gets 16. The failure is in code that never mentionsSquare. - Anemic interface segregation. Splitting one fat interface into ten micro-interfaces that always travel together just moves the bloat to the implements clause. Segregate by who calls what, not arbitrarily.
When to apply SOLID, and when not to
SOLID is not free — every abstraction you add is indirection a reader must follow and a class a maintainer must navigate. The senior decision is where to spend it, governed by one question: is this a place that has changed, or is genuinely likely to change, along a known axis?
- Reach for it when you can name the axis of change: "we add a new payment provider every quarter" (OCP via strategy), "we must swap the datastore / mock it in tests" (DIP), "three teams edit one class for unrelated reasons" (SRP). The signal is a real, recurring or near-certain variation point.
- Prefer the blunt alternative when the axis is speculative. A plain
if/elseor a single concrete class with no interface is the right call for a discount rule that has had one value for two years. This is YAGNI — and YAGNI beats SOLID until the second or third variation actually arrives (the "rule of three").
Trade-off vs the alternative (YAGNI / direct code): SOLID buys you cheap, localized change at a known seam — but costs you extra types, indirection, and slower first-read comprehension. Direct code buys you immediate clarity and fewer files — but costs you a painful, wide-blast-radius edit when change finally hits.
Choose SOLID abstractions when a variation point is real and recurring (you've seen it change, or you know it will); prefer simple direct code when the variation is hypothetical — refactor toward SOLID at the moment the second variant appears, not before.
Takeaways
- SOLID's single mechanism: put each independent reason-to-change behind its own abstraction so future edits stay local.
- The letters overlap — fixing the worst class often satisfies SRP, OCP, and DIP in one move (inject dependencies, strategize the varying behavior).
- Abstraction has a cost (indirection, more classes); apply it at real change axes, not speculative ones — YAGNI wins until the second variant arrives.
- Liskov failures are invisible at compile time; they surface in callers that never name the subclass, so verify substitutability with the base type's contract, not the subclass's.
Re-authored and deepened for this guide. Sources: Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices (2002) and Clean Architecture (2017), where the SOLID acronym and the Dependency Inversion direction-flip originate; Barbara Liskov & Jeannette Wing, "A Behavioral Notion of Subtyping" (1994) for LSP; the YAGNI / rule-of-three guidance follows Martin Fowler's Refactoring (2nd ed., 2018) and the Extreme Programming literature.
🤖 Don't fully get this? Learn it with Claude
Stuck on What are SOLID Design Principles? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Build the mental picture, not memorization.
I just read a lesson on **What are SOLID Design Principles** (OO & Low-Level Design) and want to truly understand it. Explain What are SOLID Design Principles from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Socratic — adapts to where you're stuck.
Teach me **What are SOLID Design Principles** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Active recall exposes what you missed.
Quiz me on **What are SOLID Design Principles** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Intuition + hook + flashcards for long-term memory.
Help me remember **What are SOLID Design Principles** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.