Skip to lesson

SOLID principles in plain words

SOLID is a set of five design principles: short rules of thumb that keep classes easy to change. Code changes all the time, and SOLID describes designs that take a change in one small place, with names you can use in an interview or a code review.

S: single responsibility

The single responsibility principle (SRP) says a class should have only one reason to change: one job, done well. A class that calculates, prints and sends messages risks breaking one job whenever another changes.

A cook cooks; delivery is someone else's job. If a Result class calculates marks, prints the report card and sends the SMS, a change to any of the three touches it, and can break the other two.

SOLID as five cards: S, single responsibility, one reason to change; O, open/closed, add code, do not edit it; L, Liskov substitution, children keep the promises; I, interface segregation, small interfaces; D, dependency inversion, depend on interfaces.

Example 1 · S: one class per job

SrpDemo.javaJava
class Result {    private final String name;    private final int[] marks;
    Result(String name, int[] marks) {        this.name = name;        this.marks = marks;    }
    String getName() {        return name;    }
    int percent() {        int sum = 0;        for (int m : marks) {            sum += m;        }        return sum / marks.length;    }}
class ReportCardPrinter {    void print(Result r) {        System.out.println("Report card: " + r.getName() + ", " + r.percent() + "%");    }}
class ParentSms {    String message(Result r) {        return "Dear parent, " + r.getName() + " scored " + r.percent() + "%";    }}
public class SrpDemo {    public static void main(String[] args) {        Result r = new Result("Ananya", new int[] { 80, 90, 85 });        new ReportCardPrinter().print(r);        System.out.println(new ParentSms().message(r));    }}
Output
Report card: Ananya, 85%
Dear parent, Ananya scored 85%

What this code does

  • Before, one class calculated marks, printed the card and wrote the SMS: three reasons to change.
  • Now a new SMS format touches only ParentSms; a new grading rule touches only Result.

Split by reason to change, not by size: a long class with one job is fine, a short class with three jobs is not. This is the god-class fix from Spot OOP design problems (opens in a new tab), given a name.

Find the bug

One job too many

Select the line that is wrong.

Which method gives Invoice a second reason to change?

Round 1 of 2

O: open for extension, closed for modification

The open/closed principle (OCP) says a class should be open for extension but closed for modification: you add new behaviour by writing new classes, not by editing code that already works.

You can add apps to your phone without opening the phone. In code, Checkout works with an Offer interface: a new festival offer is a new class, and Checkout itself is never edited, so it cannot break.

Example 2 · O: add a new offer without editing Checkout

OcpDemo.javaJava
interface Offer {    String name();
    int apply(int amount);}
class NoOffer implements Offer {    public String name() {        return "No offer";    }
    public int apply(int amount) {        return amount;    }}
class FestivalOffer implements Offer {    public String name() {        return "Diwali 10% off";    }
    public int apply(int amount) {        return amount - amount / 10;    }}
class Checkout {    void pay(int amount, Offer offer) {        System.out.println(offer.name() + ": Rs. " + offer.apply(amount));    }}
public class OcpDemo {    public static void main(String[] args) {        Checkout c = new Checkout();        c.pay(2000, new NoOffer());        c.pay(2000, new FestivalOffer());    }}
Output
No offer: Rs. 2000
Diwali 10% off: Rs. 1800

What this code does

  • Checkout is closed: it has no if for each offer, so it never needs editing.
  • It is open: a new FlatHundredOff class plugs in through the same Offer interface.

The warning sign is an if chain on a type or a string that grows with every new case. Replace it with an interface or an abstract method, and each new case becomes one new class.

Predict the output

New offers, same Checkout

Read the code and pick what it prints.

interface Offer {
int apply(int amount);
}
class Checkout {
int pay(int amount, Offer offer) {
return offer.apply(amount);
}
}
public class OfferRound {
public static void main(String[] args) {
Checkout c = new Checkout();
Offer flat = amount -> amount >= 1000 ? amount - 150 : amount;
Offer half = amount -> amount / 2;
System.out.println(c.pay(1200, flat) + " " + c.pay(900, flat) + " " + c.pay(900, half));
}
}

L: a child must keep the parent's promises

The Liskov substitution principle (LSP) says a child object must work everywhere its parent is expected, without surprises: it keeps every promise that the parent's methods make.

A substitute teacher must be able to take the same class. In code, Penguin extends Bird overrides fly() to throw an exception, so a loop that calls fly() on every bird crashes on the penguin.

Example 3 · L broken: a child that cannot keep the promise

LspBroken.javaJava
class Bird {    void fly() {        System.out.println("Flying high");    }}
class Sparrow extends Bird {}
class Penguin extends Bird {    @Override    void fly() {        throw new UnsupportedOperationException("Penguins cannot fly");    }}
public class LspBroken {    public static void main(String[] args) {        Bird[] birds = { new Sparrow(), new Penguin() };        for (Bird b : birds) {            b.fly();        }    }}
Sample output
Flying high
Exception in thread "main" java.lang.UnsupportedOperationException: Penguins cannot fly
	at Penguin.fly(LspBroken.java:13)
	at LspBroken.main(LspBroken.java:21)

What this code does

  • Bird promises that every bird can fly(). The loop trusts that promise, so a penguin in the array crashes it.
  • javac cannot catch this: the code compiles. Only the design is wrong.

Example 4 · L fixed: the parent promises only what all children can do

LspFixed.javaJava
class Bird {    private final String name;
    Bird(String name) {        this.name = name;    }
    String eat() {        return name + " eats";    }}
class FlyingBird extends Bird {    FlyingBird(String name) {        super(name);    }
    String fly() {        return "and flies";    }}
public class LspFixed {    public static void main(String[] args) {        FlyingBird sparrow = new FlyingBird("Sparrow");        Bird penguin = new Bird("Penguin");        Bird[] all = { sparrow, penguin };        for (Bird b : all) {            System.out.println(b.eat());        }        FlyingBird[] flyers = { sparrow };        for (FlyingBird f : flyers) {            System.out.println(f.eat() + " " + f.fly());        }    }}
Output
Sparrow eats
Penguin eats
Sparrow eats and flies

What this code does

  • Bird now promises only eat(), which every bird can do. Any bird can be put anywhere a Bird is expected.
  • Only code that needs flying asks for a FlyingBird, so a penguin can never reach fly().

Fix: let the parent promise only what every child can do: move fly() into a FlyingBird class or a Flyer interface.

Warning signs: a child method that throws "not supported", does nothing, or needs instanceof checks around it. The is-a sentence may sound true, but the child cannot keep the promise.

Predict the output

Is a square a rectangle?

Read the code and pick what it prints.

The code was written for a Rect and expects 5 × 4.

class Rect {
int w, h;
void setWidth(int w) {
this.w = w;
}
void setHeight(int h) {
this.h = h;
}
int area() {
return w * h;
}
}
class Square extends Rect {
@Override
void setWidth(int side) {
w = h = side;
}
@Override
void setHeight(int side) {
w = h = side;
}
}
public class LspRound {
public static void main(String[] args) {
Rect r = new Square();
r.setWidth(5);
r.setHeight(4);
System.out.println(r.area());
}
}

I: small interfaces, not one fat one

The interface segregation principle (ISP) says no class should be forced to implement methods it does not use, so several small, focused interfaces are better than one large one.

A small restaurant does not print a menu of 200 dishes it cannot cook. A basic printer should not implement a fat OfficeMachine interface with scan() and fax(): split it into small interfaces like Printer and DocScanner.

Example 5 · I: split a fat interface

IspDemo.javaJava
interface Printer {    String print(String doc);}
interface DocScanner {    String scan(String doc);}
class BasicPrinter implements Printer {    public String print(String doc) {        return "Printed " + doc;    }}
class AllInOne implements Printer, DocScanner {    public String print(String doc) {        return "Printed " + doc + " in colour";    }
    public String scan(String doc) {        return "Scanned " + doc;    }}
public class IspDemo {    public static void main(String[] args) {        Printer[] printers = { new BasicPrinter(), new AllInOne() };        for (Printer p : printers) {            System.out.println(p.print("Admit card"));        }        DocScanner s = new AllInOne();        System.out.println(s.scan("Aadhaar copy"));    }}
Output
Printed Admit card
Printed Admit card in colour
Scanned Aadhaar copy

What this code does

  • With one fat OfficeMachine interface, BasicPrinter would have to write a fake scan() that throws an exception.
  • With two small interfaces, each class implements only what it can really do, and callers ask only for what they need.

An all-in-one machine simply implements both small interfaces, and callers ask only for the ability they need, as in Implement several interfaces (opens in a new tab).

Fix the error

A phone that cannot install apps

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

A basic phone can call but cannot install apps.

interface Caller {
void call(String number);
}
interface AppStore {
void installApp(String app);
}
interface SmartDevice extends Caller, AppStore {
}
class BasicPhone implements SmartDevice {
public void call(String number) {
System.out.println("Calling " + number);
}
}

Error

BasicPhone.java:9: error: BasicPhone is not abstract and does not override abstract method installApp(String) in AppStore
class BasicPhone implements SmartDevice {
^

D: depend on interfaces, passed in from outside

The dependency inversion principle (DIP) says important classes should depend on interfaces, not on concrete classes. The real object is passed in from outside, usually through the constructor.

A lamp plugs into a socket; it is not wired into the wall. If OrderService writes new SmsNotifier() inside itself, it is wired to SMS forever. Give it a Notifier interface through its constructor instead.

Example 6 · D: depend on an interface, passed in from outside

DipDemo.javaJava
interface Notifier {    void send(String to, String msg);}
class SmsNotifier implements Notifier {    public void send(String to, String msg) {        System.out.println("SMS to " + to + ": " + msg);    }}
class EmailNotifier implements Notifier {    public void send(String to, String msg) {        System.out.println("Email to " + to + ": " + msg);    }}
class OrderService {    private final Notifier notifier;
    OrderService(Notifier notifier) {        this.notifier = notifier;    }
    void placeOrder(String to, int amount) {        notifier.send(to, "Order of Rs. " + amount + " placed");    }}
public class DipDemo {    public static void main(String[] args) {        new OrderService(new SmsNotifier()).placeOrder("98450 12345", 450);        new OrderService(new EmailNotifier()).placeOrder("rohan@mail.com", 450);        new OrderService((to, msg) -> System.out.println("TEST: " + msg)).placeOrder("x", 1);    }}
Output
SMS to 98450 12345: Order of Rs. 450 placed
Email to rohan@mail.com: Order of Rs. 450 placed
TEST: Order of Rs. 1 placed

What this code does

  • OrderService knows only the Notifier interface. It never writes new SmsNotifier(), so it is not wired to SMS.
  • The caller injects the notifier through the constructor. A lambda makes a quick fake for testing.

Passing the object in from outside is called dependency injection. It is the usual way to follow DIP, and it lets you pass a fake notifier while testing.

SOLID is a guide, not a law. In a 50-line program, five interfaces only make the code harder to read; apply SOLID where change is likely, such as payment types or notification channels.

Order of execution

Injection, step by step

main runs the line below. Tap the steps in the order they happen.

class OrderService {
private final Notifier notifier;
OrderService(Notifier notifier) {
this.notifier = notifier;
}
void placeOrder(String to, int amount) {
notifier.send(to, "Order of Rs. " + amount + " placed");
}
}
// in main:
new OrderService(new SmsNotifier()).placeOrder("98450 12345", 450);
A lambda can stand in for a one-method interface, which makes it easy to pass a fake notifier while testing.

Next step

Check your understanding

12 quick questions