SysDesignAtlas

SOLID, in Plain English

The five principles as they're actually used in an interview — the problem each one fixes, a small before-and-after, and the sentence that earns the point.

LLDMedium11 min readsolidooplldprinciples
Confidence

SOLID is five rules of thumb for arranging classes. It isn't a checklist to recite. It's a way of justifying decisions you were going to make anyway — and that's exactly why interviewers reward it. "This feels cleaner" is an opinion; "this way, changing the email template can't break booking" is an argument they can agree with.

Learn each one as three things: the problem, the fix, and the sentence you say.

  1. 1 S · One job per class If describing it needs the word "and", split it.
  2. 2 O · Add, don't edit New behaviour should mean a new class.
  3. 3 L · Children must stand in A subclass has to work wherever the parent did.
  4. 4 I · Small interfaces Nobody should implement methods they can't support.
  5. 5 D · Depend on interfaces Take collaborators in, don't create them inside.

The first two win most of the points. The middle two are usually one-liners. The last one is what makes your design testable.

The five, in the order they matter in an LLD round.

#S — Single responsibility: one job per class

The problem: one class does several unrelated things — say, it decides whether a booking is allowed, saves it to the database and sends the confirmation email. Each of those jobs is a separate reason someone will open the file and edit it. Every edit risks breaking the other jobs living in the same class: a developer tweaking the email wording can accidentally break the booking rules sitting a few lines away.

How to spot it: two warning signs.

  • You need the word "and" to describe it. "It checks availability and saves bookings and sends emails." Each "and" is another job, and so another reason for the class to change.
  • Its methods fall into separate groups that don't use each other's data. Some methods are about the actual business rules; others are about plumbing like SQL or SMTP. When groups like that share a class, they're two classes that happen to live in one file.
java
// Three jobs: booking rules, storage, and messaging.
class BookingService {
    Booking book(...) { /* availability rules */ }
    void saveToDatabase(Booking b) { /* SQL */ }
    void sendConfirmationEmail(Booking b) { /* SMTP */ }
}

// Fixed: each helper changes for its own reason.
class BookingService {
    private final BookingRepository repo;
    private final NotificationSender notifier;

    Booking book(BookingRequest req) {
        Booking b = /* availability rules — the one job */;
        repo.save(b);
        notifier.send(new BookingConfirmed(b));
        return b;
    }
}

Say this: "The booking rules stay in the service. Storage goes behind a repository and messaging behind a sender, so changing the email template can't break availability logic."

#O — Open/closed: add rather than edit

The problem: every time a new case arrives — a new vehicle type, a new payment method — you have to go back and edit a method that already works and is already tested. Editing working code is how working code gets broken. "Open/closed" means the design is open to new behaviour but closed to edits of what's already there.

How to spot it: a switch or a chain of ifs that branches on what type of thing it was given (case BIKE, case CAR...). That's the sign because the list of types is the part that keeps growing: each new type forces you back into this method to add another case — and often into several other methods with the same switch.

java
// Every new vehicle type edits this method.
Money fee(Vehicle v, Duration d) {
    switch (v.type()) {
        case BIKE:  return rate(10, d);
        case CAR:   return rate(20, d);
        case TRUCK: return rate(40, d);
    }
    // Add a VAN type, forget this switch, and this line crashes at runtime.
    throw new IllegalStateException();
}

// Fixed: a new price rule is a new class, registered in one place.
interface PricingStrategy { Money price(Duration d); }

class FlatHourlyPricing implements PricingStrategy { /* ... */ }
class WeekendSurgePricing implements PricingStrategy { /* ... */ }

class FeeCalculator {
    private final Map<VehicleSize, PricingStrategy> strategies;
    Money fee(Vehicle v, Duration d) { return strategies.get(v.size()).price(d); }
}

Say this: "Pricing is the thing most likely to change, so it sits behind an interface. A weekend surcharge becomes a new class, and nothing that already works gets edited."

Interviewers probe this one most, because their standard follow-up — "now add X" — is a direct test of it. If your answer is "I add a class", you pass. If it's "I add a case to four different switches", you don't.

#L — Liskov substitution: a child must stand in for its parent

The idea in one line: if Square extends Rectangle, then anywhere your code uses a Rectangle, you should be able to hand it a Square instead and nothing should break.

Why it matters: when you write a method that takes an Account, you write it trusting what an Account promises — "I can deposit, I can withdraw". Inheritance lets someone pass in any subclass of Account later. If that subclass quietly breaks one of those promises, your method fails — even though you never changed it, and even though the compiler said everything was fine.

How to spot it: two warning signs.

  • A child refuses a job the parent promised. A subclass overrides a method just to throw an error like "not supported". The parent said "I can do this"; the child says "actually, I can't".
  • Callers check the exact type before using it. Code like if (account instanceof ReadOnlyAccount) { ... } else { account.withdraw(...) }. If the caller has to ask "which kind are you?" before trusting the object, the child isn't really a safe stand-in for the parent.
java
// The classic. A square is a rectangle in maths, not in behaviour.
class Rectangle { void setWidth(int w); void setHeight(int h); }
class Square extends Rectangle {
    void setWidth(int w)  { this.w = w; this.h = w; }   // also changes the height!
}

// A caller that only knows about Rectangle:
void stretch(Rectangle r) {
    r.setHeight(5);
    r.setWidth(10);
    // Expects area 50. A Square gives 100, because setWidth changed the height too.
}

// A more realistic one:
class ReadOnlyAccount extends Account {
    void withdraw(long amount) { throw new UnsupportedOperationException(); }
}

The fix: model the difference as a capability rather than a family tree — separate Readable and Writable interfaces, or have both classes implement a shared interface instead of one extending the other.

Say this: "I won't subclass here. A read-only account can't honour withdraw, so it can't stand in for an account. I'll split the interface instead."

#I — Interface segregation: keep interfaces small

The problem: one big interface lists every operation any implementation might support, so every class that implements it must provide all of them — including ones that make no sense for it. A basic printer forced to implement fax has no honest way to do so.

How to spot it: classes that implement an interface but leave half its methods empty, or make them throw "not supported". Those empty or throwing methods are the class admitting "I was forced to promise this, but I can't do it" — which means the interface is asking for more than this class is.

java
// Too big: a simple printer must implement two things it cannot do.
interface Machine { void print(Doc d); void scan(Doc d); void fax(Doc d); }

// Split: implement exactly what you are.
interface Printer { void print(Doc d); }
interface Scanner { void scan(Doc d); }

class BasicPrinter implements Printer { }
class MultiFunction implements Printer, Scanner { }

In an LLD round this is usually a single judgement call rather than a whole design. The useful rule: size an interface to what the caller needs, not to everything the implementation can do. If a class only ever calls send, give it an interface with just send — not one with connect, send, flush, close and stats. That way it can't accidentally depend on the rest, and a test only has to fake one method.

#D — Dependency inversion: take your collaborators in

The problem: a class that creates its own helpers with new — new MySqlOrderRepo() inside its own fields — is permanently tied to those exact classes. To test it you need a real MySQL database and a real mail server, because there's no way to give it anything else. And to switch databases, you have to edit the class itself.

The fix: don't let the class build its helpers ("collaborators"). Have whoever creates it pass them in as constructor arguments, typed as interfaces rather than concrete classes. This is called dependency injection, and it's less grand than it sounds — it just means "receive what you need instead of making it".

java
// Tied to MySQL and a real mail server: it builds them itself,
// so nothing else can be swapped in.
class OrderService {
    private final MySqlOrderRepo repo = new MySqlOrderRepo();
    private final SmtpMailer mailer = new SmtpMailer();
}

// Handed its collaborators instead.
class OrderService {
    private final OrderRepository repo;
    private final Mailer mailer;

    OrderService(OrderRepository repo, Mailer mailer) {   // injected
        this.repo = repo;
        this.mailer = mailer;
    }
}

Two payoffs, and they're the reason anyone cares:

  • You can test it. new OrderService(new InMemoryOrderRepo(), new FakeMailer()) — no database, no network, tests finish in milliseconds. When asked "how would you test this?", this is the answer.
  • You can swap things. In-memory today, Postgres tomorrow, and the service never notices. In an interview you can say "I'll use an in-memory repository here; swapping in a real database changes one line of wiring."

Say this: "Everything is passed in through the constructor as an interface, so I can run the whole thing in memory in a test and plug real infrastructure in at startup."

#Using these when the clock is running

You won't have time to mention all five. Name a principle at the moments where it explains a choice you just made:

When this happensName this one
You split your first big classOne job per class (S)
You put an interface where things varyAdd-don't-edit (O), and injection (D)
Asked "now add a new kind of X"Add-don't-edit — and show it, don't just claim it
Asked "how would you test this?"Dependency injection (D)
You catch yourself writing instanceofSubstitution (L) — say why you're avoiding it

#Check yourself

What does single responsibility actually mean — and not mean?Show answer
One reason to change: business rules, storage, display and outside systems belong apart. It does not mean tiny classes — if you can't name a second reason to change, don't split.
How do you spot an open/closed violation, and fix it?Show answer
A switch or if-chain on a type that every new case must edit. Put the varying behaviour behind an interface so a new case is a new class.
Which switch is allowed under open/closed?Show answer
Exactly one, at the edge — a factory, registry or config table that turns input into the right object — instead of switches scattered through the middle.
What is a Liskov substitution violation, and the fix?Show answer
A subclass that breaks when used where the parent was expected: it overrides a method just to throw "not supported", or callers must check instanceof before trusting it. Fix: model capabilities as separate interfaces instead of making one class extend the other.
What does interface segregation say in one rule?Show answer
Size an interface to what the caller needs, not to everything the implementation can do, so nobody implements methods they can't support.
What is dependency inversion, and its two payoffs?Show answer
Take collaborators in through the constructor, typed as interfaces, instead of creating them with new. You can test with in-memory fakes, and swap infrastructure by changing one line of wiring.
How should you mention SOLID in an interview?Show answer
State the consequence, not the acronym: "changing how we charge cards can't break spot allocation." Reciting principle names sounds memorised and invites challenge.

#What to carry forward

  • SOLID justifies decisions you'd make anyway — use it to turn "cleaner" into an argument.
  • S and O win most points: one reason to change per class, and new behaviour as a new class.
  • L and I are usually one-liners: don't subclass if the child can't do everything the parent promises; keep each interface as small as its caller needs.
  • D makes the design testable: inject interfaces through the constructor.
  • Say the consequence, not the label.
00:00
/ 11m