Single Responsibility — One class, one reason to change
One reason to change per class — split when fixes touch unrelated features. · Small classes are easier to test and reuse.
Watch
Watch, then scroll down for code and practice.
In code
class LogFormatter {
format(level: string, msg: string) {
return `[${level}] ${msg}`;
}
}
class FileLogWriter {
append(line: string) {
/* write to disk */
}
}
class Logger {
constructor(
private fmt: LogFormatter,
private writer: FileLogWriter
) {}
info(msg: string) {
this.writer.append(this.fmt.format("INFO", msg));
}
}📘 Key ideas
The principle
A class should have one, and only one, reason to change. If changing the log format also requires touching the class that sends emails — SRP is violated.
How to spot violations
The class name contains 'And' or 'Manager'. It has more than ~5 public methods. Changes to unrelated features keep touching it.
Fix: extract responsibilities
LogFormatter (formatting), FileHandler (IO), LogFilter (level logic) — each has one job. Logger orchestrates them.
Side effect: testability
SRP classes are trivially unit-testable — they do one thing, so mocking is easy and tests are small.
🧠 Practice — Apply What You Learned
SRP: Fix the Overloaded Logger
You are given a Logger class that does too much: it formats log messages, filters by level…
OCP: Extend Discounts Without Modifying
A PriceCalculator class uses a long if-else chain to apply discounts: if user is Student, …
LSP: The Square–Rectangle Problem
The classic LSP violation: Square extends Rectangle. Since a square's width and height mus…
ISP: Break the Fat Worker Interface
A Worker interface has four methods: work(), eat(), sleep(), requestLeave(). HumanWorker i…
DIP: Decouple the Database Layer
UserService directly instantiates MySQLDatabase inside its constructor: `this.db = new MyS…
Logger / Logging Framework
Design a flexible logging framework that supports multiple log levels, formatters, and out…
Payment Gateway
Design a payment processing system that handles transactions across multiple payment metho…
🚀 Now apply what you learned
Pick a problem above, write your solution, and get AI feedback on your design.
Start Practice →