AdvancedSoftware Engineering · Lesson 9 of 13 · Updated ·
SOLID Principles — Single Responsibility, Open-Closed, Liskov, Interface Segregation, Dependency Inversion
In the design lesson you met coupling (how much modules depend on each other) and cohesion (how focused one module is). SOLID is a set of five rules, collected by Robert C. Martin, that turn those ideas into everyday decisions about classes. They are asked in almost every interview for a developer role, usually as "explain SOLID with an example".
| Letter | Principle | One-line meaning |
|---|---|---|
| S | Single Responsibility | a class should have only one reason to change |
| O | Open-Closed | add new behaviour by adding code, not by editing working code |
| L | Liskov Substitution | a child class must work wherever the parent is expected |
| I | Interface Segregation | many small interfaces are better than one fat one |
| D | Dependency Inversion | depend on abstractions, not on concrete classes |
1. Single Responsibility Principle (SRP)
A "responsibility" is a reason to change. Look at this class from a college results system:
class ResultCard:
def __init__(self, name, marks):
self.name, self.marks = name, marks
def percentage(self): # rule from the exam cell
return sum(self.marks) / len(self.marks)
def as_text(self): # layout wanted by the office
return f'{self.name}: {self.percentage():.1f}%'
def save(self, store): # storage chosen by the IT team
store.append(self.as_text())
store = []
ResultCard('Asha', [78, 91, 85]).save(store)
print(store)
['Asha: 84.7%']
Three different people can force a change here: the exam cell (grading rule), the office (layout) and the IT team (database). A change for one of them risks breaking the others. SRP says: split it so that each class has one owner.
class Grading:
@staticmethod
def percentage(marks):
return sum(marks) / len(marks)
class ResultFormatter:
@staticmethod
def as_text(name, pct):
return f'{name}: {pct:.1f}%'
class ResultStore:
def __init__(self):
self.rows = []
def save(self, line):
self.rows.append(line)
store = ResultStore()
pct = Grading.percentage([78, 91, 85])
store.save(ResultFormatter.as_text('Asha', pct))
print(store.rows)
['Asha: 84.7%']
The output is the same. What changed is that the grading rule can now be edited and tested without touching storage code. SRP is high cohesion applied to a class.
2. Open-Closed Principle (OCP)
Software should be open for extension, closed for modification. A shop's billing code that grows an if for every new offer breaks this rule — every new festival offer means editing (and re-testing) the same function. Instead, give each offer its own class with the same method:
class NoOffer:
def apply(self, amount):
return amount
class FlatOff:
def __init__(self, off):
self.off = off
def apply(self, amount):
return max(0, amount - self.off)
class PercentOff:
def __init__(self, pct):
self.pct = pct
def apply(self, amount):
return amount * (100 - self.pct) / 100
def bill(amount, offer):
return offer.apply(amount) # never changes when a new offer is added
for offer in [NoOffer(), FlatOff(200), PercentOff(10)]:
print(type(offer).__name__, bill(1500, offer))
NoOffer 1500
FlatOff 1300
PercentOff 1350.0
A new "buy 2 get 1" offer is a new class; bill() is not touched. This is how plug-ins, payment gateways and the Strategy design pattern work.
3. Liskov Substitution Principle (LSP)
Barbara Liskov's rule: if S is a subclass of T, then objects of T can be replaced by objects of S without breaking the program. Inheritance must model "behaves like", not just "is a kind of" in plain English. The classic trap:
class Rectangle:
def __init__(self, w, h):
self.w, self.h = w, h
def set_width(self, w):
self.w = w
def area(self):
return self.w * self.h
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
def set_width(self, w): # a square must keep both sides equal
self.w = self.h = w
def stretch(rect): # written for Rectangle
rect.set_width(10)
return rect.area() # caller expects 10 * old height
print(stretch(Rectangle(4, 5)))
print(stretch(Square(5)))
50
100
The function expected 10 × 5 = 50 both times. Square changed the meaning of set_width, so it is not substitutable. Fixes: don't make Square a subclass of a mutable Rectangle; make both subclasses of a Shape with only area(), or make shapes immutable.
Signs that LSP is broken: a subclass method that raises NotImplementedError for an inherited method, needs stricter inputs, or returns something the parent never would.
4. Interface Segregation Principle (ISP)
No class should be forced to depend on methods it does not use. Suppose an office-machine interface has print_doc, scan and fax. A cheap printer that can only print must still "implement" scan and fax — usually by raising errors, which also breaks LSP. Split the interface:
| Fat interface | Segregated interfaces |
|---|---|
Machine: print_doc, scan, fax | Printer: print_doc |
Scanner: scan | |
Fax: fax | |
| Basic printer fakes scan and fax | Basic printer implements only Printer; an all-in-one implements all three |
In Python you often express this with small abstract base classes; in Java, with small interfaces.
5. Dependency Inversion Principle (DIP)
- High-level modules (business rules) should not depend on low-level modules (email, database, SMS). Both should depend on an abstraction.
- The abstraction should not depend on details; details depend on the abstraction.
from abc import ABC, abstractmethod
class MessageSender(ABC):
@abstractmethod
def send(self, to, text): ...
class EmailSender(MessageSender):
def send(self, to, text):
print(f'EMAIL to {to}: {text}')
class FakeSender(MessageSender): # used in tests: records instead of sending
def __init__(self):
self.sent = []
def send(self, to, text):
self.sent.append((to, text))
class FeeReminder: # high-level rule
def __init__(self, sender: MessageSender):
self.sender = sender # injected from outside
def remind(self, students):
for name, due in students:
if due > 0:
self.sender.send(name, f'Fee due: Rs {due}')
students = [('Ravi', 2500), ('Neha', 0)]
FeeReminder(EmailSender()).remind(students)
fake = FakeSender()
FeeReminder(fake).remind(students)
print(fake.sent)
EMAIL to Ravi: Fee due: Rs 2500
[('Ravi', 'Fee due: Rs 2500')]
Passing the sender in through the constructor is called dependency injection. It is the usual way to apply DIP, and it is what makes unit testing easy: the test uses FakeSender, so no real email is sent. Frameworks such as Spring (Java) and NestJS do this injection for you.
6. Three more rules you will hear
| Rule | Meaning | Example |
|---|---|---|
| DRY — Don't Repeat Yourself | every piece of knowledge has one home | the GST rate is defined once, not typed in ten files |
| KISS — Keep It Simple | prefer the simplest design that works | a dictionary, not a custom class hierarchy, for a lookup table |
| YAGNI — You Aren't Gonna Need It | don't build features "for later" | no plug-in system for a one-off script |
SOLID and YAGNI pull in opposite directions. Five tiny classes for a 30-line script is over-engineering. Apply SOLID where change is likely: business rules, external services, anything that will be tested in isolation.
Common mistakes
- Reading SRP as "a class should have one method". It means one reason to change (one owner), not one function.
- Using inheritance only because the English words fit ("a square is a rectangle"). LSP is about behaviour.
- Confusing dependency inversion (a design principle) with dependency injection (a technique to achieve it).
- Implementing an interface method with
raise NotImplementedError— a sign the interface is too fat (ISP). - Applying every principle everywhere. Extra abstraction has a cost; use it where change is expected.
Quick recap
- S: one reason to change per class. O: extend by adding classes, not by editing working code.
- L: subclasses must keep the parent's promises. I: small, focused interfaces.
- D: business logic depends on abstractions; concrete details are injected.
- SOLID gives low coupling and high cohesion, which make code easier to test and change.
- Balance SOLID with KISS and YAGNI.