CMD Guide
HomeOO & Low-Level DesignSOLID Principles

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.

LetterNameThe rule in one lineThe smell when you break it
SSingle ResponsibilityA 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.
OOpen/ClosedAdd new behavior by adding code, not by editing tested code.Every new payment type means another branch in one growing if/else.
LLiskov SubstitutionAny subtype must be usable wherever the base type is, with no surprises.Square extends Rectangle breaks code that sets width and height independently.
IInterface SegregationDon't force a client to depend on methods it never calls.A read-only consumer must stub out write() to compile.
DDependency InversionHigh-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.

StepOperationRunning value
12 × $30 (widgets)sum = 60.00
2+ 1 × $20 (cable)sum = 80.00
3× PremiumDiscount.factor() = 0.90sum = 72.00
4store.save("ORD-7", 72.00)persisted via injected store
5notifier.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.

diagram
diagram

Pitfalls

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?

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


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.

🎨 Explain it visually

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.
🤔 Walk me through it (interactive)

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.
🧪 Quiz me & fix my gaps

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.
🧠 Make it stick

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.

📝 My notes