Skip to lesson

SOLID in One Minute Each

Interviewers ask about SOLID as one question with one follow-up, and again inside design rounds. They check whether you can give a one-minute answer with a before and after, not just five names.

One-minute answers with a tiny before/after

SOLID is a set of five design principles for object-oriented code that is easy to change: Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion.

Each answer has the same shape: the principle in one sentence, a small before that breaks it, the after that fixes it, and the benefit. The table gives all five.

Example 1 · The five one-minute answers

Text
S  Single responsibility: one reason to change.   Before: StudentService calculates fees, sends email, writes PDF.   After:  FeeCalculator, EmailNotifier, ReceiptPdf.O  Open/closed: extend by adding, not editing.   Before: if (type == STUDENT) ... else if (type == FESTIVAL) ...   After:  interface DiscountPolicy; one class per discount.L  Liskov substitution: subclass works wherever parent works.   Before: Square extends Rectangle with setWidth/setHeight.   After:  interface Shape { area(); } with separate classes.I  Interface segregation: small, focused interfaces.   Before: interface Machine { print(); scan(); fax(); }   After:  Printer, Scanner, Fax.D  Dependency inversion: depend on interfaces, inject implementations.   Before: OrderService does new RazorpayGateway().   After:  OrderService(PaymentGateway gateway) via constructor.
Pattern
Principle -> before -> after -> benefit, under a minute each.

What this code does

  • Say these aloud with a timer; each takes about 20 to 40 seconds with its before and after.
  • Pick class names from your own project where you can; a real example is more convincing than a textbook one.

Keep each answer under a minute and let the interviewer pick one to go deeper.

Must know:

  • S: one class, one reason to change
  • O: add new behaviour by adding classes, not by editing tested code
  • L: a subclass must work anywhere its parent works
  • I: small focused interfaces; D: depend on interfaces and receive implementations from outside

Single responsibility and open/closed: the discount example

SRP, the Single Responsibility Principle, says a class should have one reason to change, meaning one job. A class that calculates, formats and saves changes whenever any of the three changes.

Open/closed says a new discount should be a new class, not another branch in a growing if-else. One refactor fixes both: a DiscountPolicy interface with one class per discount.

Example 2 · Discounts: before and after SRP and OCP

SrpOcpDemo.javaJava
import java.util.List;
// Before: one class, many reasons to change, and an if-else that growsclass BillingBefore {    String bill(String customerType, int amount) {        int discount;        if (customerType.equals("STUDENT")) {            discount = amount * 10 / 100;        } else if (customerType.equals("FESTIVAL")) {            discount = amount * 20 / 100;        } else {            discount = 0;        }        return "Pay Rs " + (amount - discount);    }}
// After: each discount is its own class; Billing only applies a policyinterface DiscountPolicy {    int discount(int amount);}
class StudentDiscount implements DiscountPolicy {    public int discount(int amount) { return amount * 10 / 100; }}
class FestivalDiscount implements DiscountPolicy {    public int discount(int amount) { return amount * 20 / 100; }}
class AlumniDiscount implements DiscountPolicy {      // added later: no edits elsewhere    public int discount(int amount) { return Math.min(500, amount * 15 / 100); }}
class Billing {    int payable(int amount, DiscountPolicy policy) {        return amount - policy.discount(amount);    }}
public class SrpOcpDemo {    public static void main(String[] args) {        System.out.println("Before: " + new BillingBefore().bill("STUDENT", 2000));
        Billing billing = new Billing();        List<DiscountPolicy> policies = List.of(new StudentDiscount(), new FestivalDiscount(), new AlumniDiscount());        for (DiscountPolicy p : policies) {            System.out.println(p.getClass().getSimpleName() + ": Rs " + billing.payable(5000, p));        }    }}
Output
Before: Pay Rs 1800
StudentDiscount: Rs 4500
FestivalDiscount: Rs 4000
AlumniDiscount: Rs 4500

What this code does

  • BillingBefore must be edited for every new customer type and also owns the output format: two reasons to change, and a growing if-else.
  • After the refactor, AlumniDiscount was added without touching Billing or the other policies (open/closed), and Billing only does billing (single responsibility).

A Billing class that calculates discounts, formats the bill and saves it changes whenever pricing, layout or storage changes. After the refactor, Billing only applies a policy.

A new "alumni" discount is one new class, and Billing is never touched.

Find the bug

Which principle is broken?

Tap the line that causes the design problem.

Every new discount type edits this method. Which line grows each time?

Round 1 of 2

Liskov: the square-rectangle question

LSP, the Liskov Substitution Principle, says a subclass must keep its parent's promises, so code that works with the parent also works with the child. Square extending a mutable Rectangle breaks it.

The classic question is "should Square extend Rectangle?". The code shows the break and the fix with a Shape interface.

Example 3 · Square vs Rectangle: the Liskov break and the fix

LiskovDemo.javaJava
class Rectangle {    protected int width, height;
    void setWidth(int w) { width = w; }    void setHeight(int h) { height = h; }    int area() { return width * height; }}
class Square extends Rectangle {    @Override    void setWidth(int w) { width = w; height = w; }    // must keep sides equal    @Override    void setHeight(int h) { width = h; height = h; }}
interface Shape {    int area();}
record Rect(int width, int height) implements Shape {    public int area() { return width * height; }}
record Sq(int side) implements Shape {    public int area() { return side * side; }}
public class LiskovDemo {    static void resizeTo5x4(Rectangle r) {        r.setWidth(5);        r.setHeight(4);        System.out.println(r.getClass().getSimpleName() + ": expected 20, got " + r.area());    }
    public static void main(String[] args) {        resizeTo5x4(new Rectangle());        resizeTo5x4(new Square());                       // breaks the caller's expectation
        Shape[] shapes = {new Rect(5, 4), new Sq(4)};        for (Shape s : shapes) {            System.out.println(s + " area " + s.area());        }    }}
Output
Rectangle: expected 20, got 20
Square: expected 20, got 16
Rect[width=5, height=4] area 20
Sq[side=4] area 16

What this code does

  • resizeTo5x4 is correct for any real rectangle, but a Square gives 16: it cannot be substituted for Rectangle, so the inheritance violates Liskov.
  • With a Shape interface and separate immutable records, there are no setters whose promises a square could break, and each shape computes its own area.

If Rectangle has setWidth and setHeight, a Square must keep both equal, so code that sets width 5 and height 4 expects area 20 but gets 16.

The answer interviewers want: "No, not with independent setters, because a square cannot keep the rectangle's promise. I would use a Shape interface with area() and separate immutable Rectangle and Square classes."

Predict the output

Can the child replace the parent?

Predict the exact output, then read the reason.

Round 1 of 2

Code written for Rectangle is given a Square.

class Rectangle {
int w, h;
void setW(int w) { this.w = w; }
void setH(int h) { this.h = h; }
int area() { return w * h; }
}
class Square extends Rectangle {
@Override
void setW(int w) { this.w = w; this.h = w; }
@Override
void setH(int h) { this.w = h; this.h = h; }
}
public class Round1 {
public static void main(String[] args) {
Rectangle r = new Square();
r.setW(6);
r.setH(3);
System.out.println(r.area());
}
}

Interface segregation and dependency inversion in Spring terms

DIP, the Dependency Inversion Principle, says high-level code should depend on abstractions, not on concrete classes. An OrderService takes a PaymentGateway interface instead of creating a RazorpayGateway.

Interface segregation splits one big interface into small ones. Dependency inversion makes a service receive its collaborator through the constructor. One example shows both.

Example 4 · Interface segregation and dependency inversion

IspDipDemo.javaJava
// Interface segregation: small interfaces instead of one fat Machineinterface Printer { String print(String doc); }interface Scanner { String scan(); }
class BasicPrinter implements Printer {    public String print(String doc) { return "Printed " + doc; }}
class OfficeMachine implements Printer, Scanner {    public String print(String doc) { return "Office printed " + doc; }    public String scan() { return "Scanned page"; }}
// Dependency inversion: OrderService depends on an abstractioninterface PaymentGateway { boolean charge(String orderId, int amount); }
class OrderService {    private final PaymentGateway gateway;
    OrderService(PaymentGateway gateway) {        this.gateway = gateway;    }
    String placeOrder(String id, int amount) {        return gateway.charge(id, amount) ? id + " confirmed" : id + " payment failed";    }}
class FakeGateway implements PaymentGateway {            // used in tests    public boolean charge(String orderId, int amount) { return amount <= 1000; }}
public class IspDipDemo {    public static void main(String[] args) {        Printer p = new BasicPrinter();        System.out.println(p.print("hall-ticket.pdf"));        System.out.println(new OfficeMachine().scan());
        OrderService service = new OrderService(new FakeGateway());        System.out.println(service.placeOrder("ORD-1", 799));        System.out.println(service.placeOrder("ORD-2", 4500));    }}
Output
Printed hall-ticket.pdf
Scanned page
ORD-1 confirmed
ORD-2 payment failed

What this code does

  • BasicPrinter implements only Printer; with one fat interface it would need a dummy scan() that throws or does nothing.
  • OrderService never names a concrete gateway. Here a fake is passed in; in Spring, the container would pass the real bean through the same constructor.

Interface segregation: do not force classes to implement methods they do not need. A basic printer should not implement scan and fax. Spring Data does the same with Repository, CrudRepository and PagingAndSortingRepository.

Dependency inversion: an OrderService takes a PaymentGateway in its constructor instead of calling new RazorpayGateway(). In Spring the container injects the real bean; in a test you pass a fake. That is constructor injection, the technique that applies the principle.

Fix the error

Fix the design error

Read the real javac error, then pick the line that fixes it.

Round 1 of 2

A basic printer is forced to implement scanning too.

interface Printer { void print(); }
interface Scan { void scan(); }
interface Machine extends Printer, Scan { }
class BasicPrinter implements Machine {
public void print() { }
}

Error

Round1.java:5: error: BasicPrinter is not abstract and does not override abstract method scan() in Scan
class BasicPrinter implements Machine {
^

Interview angle: where SOLID comes up next

In a fresher OOP round, SOLID is usually one question with one follow-up: define the principles, then explain one with code. In low-level design rounds it appears inside a design.

Example 5 · Naming SOLID during a design answer

Text
Q: "Design the fee part of a parking lot."Weak:  "I will follow SOLID principles." (and nothing else)Strong (said while drawing):  "Fees differ for bikes, cars and trucks, and new vehicle types   may come, so FeeStrategy is an interface with one class per   type. The calculator never changes: open/closed.   ParkingLot only tracks spots; fee logic and ticket printing are   separate classes: single responsibility.   ParkingService gets FeeStrategy and TicketRepository through its   constructor, so I can test it with fakes: dependency inversion."
Rule
Name the principle at the moment it explains a decision.

What this code does

  • Saying "I follow SOLID" scores nothing; tying each split to a principle shows you understand why the design looks the way it does.
  • Section 19 Low-Level Design Interview Problems practises this on complete designs such as a parking lot and a library system.

Say it as you design, not as a lecture: "fees vary by vehicle type, so FeeStrategy is an interface, that is open/closed." You justify each interface or class split by naming the principle it follows.

The design patterns behind these moves are covered in Section 19, and full problems in Section 19 Low-Level Design Interview Problems.

Order of execution

Name SOLID inside a design

Put the steps of a strong low-level design answer in order.

Next step

Check your understanding

12 quick questions