SOLID principles in plain words
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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.
Example 1 · S: one class per job
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)); }}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 onlyResult.
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 2O: 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
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()); }}No offer: Rs. 2000 Diwali 10% off: Rs. 1800
What this code does
Checkoutis closed: it has noiffor each offer, so it never needs editing.- It is open: a new
FlatHundredOffclass plugs in through the sameOfferinterface.
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.
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
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(); } }}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
Birdpromises that every bird canfly(). 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
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()); } }}Sparrow eats Penguin eats Sparrow eats and flies
What this code does
Birdnow promises onlyeat(), which every bird can do. Any bird can be put anywhere aBirdis expected.- Only code that needs flying asks for a
FlyingBird, so a penguin can never reachfly().
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.
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
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")); }}Printed Admit card Printed Admit card in colour Scanned Aadhaar copy
What this code does
- With one fat
OfficeMachineinterface,BasicPrinterwould have to write a fakescan()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.
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
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); }}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
OrderServiceknows only theNotifierinterface. It never writesnew 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.
Next step
Check your understanding
12 quick questions