These are the notes for Low-Level Design (LLD) episode 12, and the start of a new chapter: SOLID, five design principles every interviewer expects you to know. Today is the S: the Single Responsibility Principle (SRP), the most quoted and the most misunderstood of the five. We break a college office's code with one innocent change and invent the principle from the damage: responsibility, reason to change, actors, the god class, separating persistence, formatting and business logic, refactoring an SRP violation safely, why over-splitting is not SRP, and cohesion revisited. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. What SOLID is
A principle is a rule of thumb, not a law: it tells you which designs tend to hurt later. SOLID is an acronym (a word made from the first letters of other words); each letter names one principle for designing classes:
| Letter | Principle | Episode |
|---|---|---|
| S | Single Responsibility | today |
| O | Open-Closed | next |
| L | Liskov Substitution | later |
| I | Interface Segregation | later |
| D | Dependency Inversion | later |
History: the principles were collected by Robert C. Martin in his 2000 paper Design Principles and Design Patterns. Michael Feathers later arranged their initials into the word SOLID, around 2004.
2. The problem: one clerk does everything
A college office has one clerk and one big register. He calculates fees for the accounts office, writes report cards for the exam cell, and files records for the IT team. The exam cell asks: "on report cards, count medical leave as present". He edits the attendance column, the one everybody reads. And the accounts office's attendance fines quietly disappear.
The same story in code. Two terms first:
- SQL (Structured Query Language) is the language used to talk to a database (a program that stores data permanently).
INSERT INTO students VALUES (...)adds a row. In the video we print a shortenedINSERT ('Ravi', 52000)line instead of running real SQL. - A helper method is a small method other methods in the class call to avoid repeating work.
class StudentRecord {
final String name;
final int present, medical, total; // days
StudentRecord(String n, int p, int m, int t) { name = n; present = p; medical = m; total = t; }
int attendance() { return 100 * present / total; } // shared helper
int fee() { // accounts office: shortage fine below 75%
return 50000 + (attendance() < 75 ? 2000 : 0);
}
String reportCard() { // exam cell
return name + ": attendance " + attendance() + "%";
}
void save() { // IT team
System.out.println("SQL: INSERT ('" + name + "', " + fee() + ")");
}
}
public class Main {
public static void main(String[] args) {
StudentRecord ravi = new StudentRecord("Ravi", 60, 20, 100);
System.out.println(ravi.reportCard());
System.out.println("Fee: Rs " + ravi.fee());
ravi.save();
}
}
Ravi: attendance 60%
Fee: Rs 52000
SQL: INSERT ('Ravi', 52000)
attendance()turns days into a percentage: 100 x 60 / 100 = 60%.fee(): Rs 50,000, plus a Rs 2,000 shortage fine below 75% attendance. That's the accounts office's rule. (cond ? a : bgivesaif the condition is true, elseb.)reportCard(): the exam cell's text.save(): the IT team's database row.
Ravi was present 60 days and on medical leave 20, out of 100. Today everything is correct.
Now the exam cell's request: count medical leave. The developer finds the attendance helper and adds medical days. One line:
class StudentRecord {
final String name;
final int present, medical, total; // days
StudentRecord(String n, int p, int m, int t) { name = n; present = p; medical = m; total = t; }
int attendance() { return 100 * (present + medical) / total; } // exam cell's change
int fee() { // accounts office: shortage fine below 75%
return 50000 + (attendance() < 75 ? 2000 : 0);
}
String reportCard() { // exam cell
return name + ": attendance " + attendance() + "%";
}
void save() { // IT team
System.out.println("SQL: INSERT ('" + name + "', " + fee() + ")");
}
}
public class Main {
public static void main(String[] args) {
StudentRecord ravi = new StudentRecord("Ravi", 60, 20, 100);
System.out.println(ravi.reportCard());
System.out.println("Fee: Rs " + ravi.fee());
ravi.save();
}
}
Ravi: attendance 80%
Fee: Rs 50000
SQL: INSERT ('Ravi', 50000)
The report card says 80%, exactly what the exam cell wanted. But the fee dropped to Rs 50,000: Ravi's fine is gone, and the database saved the wrong fee too. Nobody in accounts asked for this, and no error appeared anywhere. One edit for the exam cell broke the accounts office.
3. Responsibility, reason to change, actor
Three different groups depend on this one class:
| Group | Uses |
|---|---|
| Accounts office | fee() |
| Exam cell | reportCard() |
| IT team | save() |
- A responsibility is a job a class does for someone. Computing fees is one; formatting report cards is another.
- A reason to change is a request that forces you to edit the class. "Count medical leave on report cards" was one.
- An actor is the person or group who makes those requests. Accounts changes fee rules; the exam cell changes report formats; the IT team changes databases.
The Single Responsibility Principle: "there should never be more than one reason for a class to change". Martin's later, sharper wording: "a module should be responsible to one, and only one, actor". (A module here means a class, or a small group of code that is changed together.)
Our class served three actors and shared code (attendance()) between them, so one actor's change hit another.
| At the college | In Java | Kind of code | Actor |
|---|---|---|---|
| Accounts counter, follows the finance officer | FeeCalculator |
business logic | accounts office |
| Exam cell window, follows the controller of exams | ReportCardFormatter |
formatting | exam cell |
| Records room, follows the IT head | StudentRepository |
persistence | IT team |
A well-run college has separate counters: a new exam rule changes one window, and the fee counter never notices.
4. The god class
A class that grows to know and do everything is called a god class. It is a code smell: a pattern in code that hints at a design problem. Signs:
| Sign | Example |
|---|---|
| Knows and does everything | StudentRecord, CollegeManager, Utils (names like Manager, Helper or Utils are an early warning) |
| Hundreds or thousands of lines, still growing | every new feature has an obvious home: there |
| Many actors edit the same file | merge conflicts every week |
| Hard to test | testing one fee rule needs a database |
| Changes cause surprises | like Ravi's fine |
- Version control is a tool that tracks every change to the code and lets a team work on it at the same time.
- A merge conflict happens when two people change the same lines of the same file, and the tool can't combine the changes automatically.
- A test is code that runs your code with known inputs and checks the outputs (see Practice 1).
5. The split: business logic, formatting, persistence
| Kind of code | Plain meaning | Our class |
|---|---|---|
| Business logic | The rules of the domain itself (fees, fines, discounts) | FeeCalculator |
| Formatting | Turning data into text or layouts for people | ReportCardFormatter |
| Persistence | Storing data so it survives after the program ends (database, file) | StudentRepository |
A repository is a class whose only job is saving and loading objects. Student becomes a record (episode 3): a compact, immutable data class; record Student(String name, int present, int medical, int total) automatically gets a constructor and accessor methods like s.present().
record Student(String name, int present, int medical, int total) { }
class FeeCalculator { // business logic: answers to the accounts office
int fee(Student s) {
int pct = 100 * s.present() / s.total();
return 50000 + (pct < 75 ? 2000 : 0);
}
}
class ReportCardFormatter { // formatting: answers to the exam cell
String format(Student s) {
int pct = 100 * (s.present() + s.medical()) / s.total();
return s.name() + ": attendance " + pct + "%";
}
}
class StudentRepository { // persistence: answers to the IT team
void save(Student s, int fee) {
System.out.println("SQL: INSERT ('" + s.name() + "', " + fee + ")");
}
}
public class Main {
public static void main(String[] args) {
Student ravi = new Student("Ravi", 60, 20, 100);
int fee = new FeeCalculator().fee(ravi);
System.out.println(new ReportCardFormatter().format(ravi));
System.out.println("Fee: Rs " + fee);
new StudentRepository().save(ravi, fee);
}
}
Ravi: attendance 80%
Fee: Rs 52000
SQL: INSERT ('Ravi', 52000)
Attendance 80% on the report card, and the fee back to Rs 52,000. Both actors get what they asked for.
Accidental duplication
The two percentage calculations look alike. That's not a mistake to remove: they are two different rules, owned by two actors, that happen to look similar today. Merging them is exactly what broke us. Code that looks the same but changes for different reasons is called accidental duplication. Keep it apart. (Real duplication, the same rule copied for the same actor, should still be merged.)
| Before: god class | After: one actor each |
|---|---|
int attendance() (shared!) |
record Student(...): data |
int fee(): accounts |
FeeCalculator.fee(): logic |
String reportCard(): exam cell |
ReportCardFormatter.format(): text |
void save(): IT team |
StudentRepository.save(): storage |
| 3 reasons to change | 1 reason to change each |
This three-way split (logic, formatting, persistence) is the most common SRP fix you'll make in machine-coding rounds (interview rounds where you write a working, well-designed program in a fixed time, episode 1).
6. Refactoring safely
Refactoring means changing the structure of code without changing its behaviour. Real projects have old code: forty places still call ravi.fee(). Paste one of them under the new design:
record Student(String name, int present, int medical, int total) { }
class FeeCalculator { // business logic: answers to the accounts office
int fee(Student s) {
int pct = 100 * s.present() / s.total();
return 50000 + (pct < 75 ? 2000 : 0);
}
}
class ReportCardFormatter { // formatting: answers to the exam cell
String format(Student s) {
int pct = 100 * (s.present() + s.medical()) / s.total();
return s.name() + ": attendance " + pct + "%";
}
}
class StudentRepository { // persistence: answers to the IT team
void save(Student s, int fee) {
System.out.println("SQL: INSERT ('" + s.name() + "', " + fee + ")");
}
}
public class Main {
public static void main(String[] args) {
Student ravi = new Student("Ravi", 60, 20, 100);
System.out.println("Fee: Rs " + ravi.fee()); // old code, 40 places
}
}
Main.java:23: error: cannot find symbol
System.out.println("Fee: Rs " + ravi.fee()); // old code, 40 places
^
symbol: method fee()
location: variable ravi of type Student
1 error
"Cannot find symbol" means the compiler can't find that name: Student has no fee() method. The fee moved out, and every old caller breaks at once. Changing everything in one giant step like this is called a big-bang refactor.
Refactor in small steps instead. Keep StudentRecord, but turn it into a thin facade: a front class that keeps the old methods and simply delegates (episode 11) to the new classes, with no logic of its own.
record Student(String name, int present, int medical, int total) { }
class FeeCalculator {
int fee(Student s) {
int pct = 100 * s.present() / s.total();
return 50000 + (pct < 75 ? 2000 : 0);
}
}
class ReportCardFormatter {
String format(Student s) {
int pct = 100 * (s.present() + s.medical()) / s.total();
return s.name() + ": attendance " + pct + "%";
}
}
class StudentRecord { // thin facade: old API, no logic of its own
private final Student s;
private final FeeCalculator fees = new FeeCalculator();
private final ReportCardFormatter cards = new ReportCardFormatter();
StudentRecord(String n, int p, int m, int t) { s = new Student(n, p, m, t); }
int fee() { return fees.fee(s); }
String reportCard() { return cards.format(s); }
}
public class Main {
public static void main(String[] args) {
StudentRecord ravi = new StudentRecord("Ravi", 60, 20, 100); // old code, unchanged
System.out.println(ravi.reportCard());
System.out.println("Fee: Rs " + ravi.fee());
}
}
Ravi: attendance 80%
Fee: Rs 52000
Old code, unchanged, and correct results. An API (application programming interface) is the set of methods other code calls; the facade keeps the old API alive. Now move the callers to the new classes one by one, and delete the facade when nobody uses it.
The recipe: refactoring an SRP violation
- List every method and ask: who asks for changes to it?
- Group the methods by actor.
- Extract one class per group; split any helper two actors share.
- Keep a thin facade so old callers still compile.
- Run and compare the output after every small step.
- Move callers over, then delete the facade.
7. Over-splitting is not SRP
A common misreading: "single responsibility" means "one method per class". Four classes for one fee rule:
// over-split: one actor's rule scattered (low cohesion)
class BaseFeeProvider { ... }
class ShortageChecker { ... }
class FineAdder { ... }
class FeeTotaller { ... }
// just right: one actor's rules together (high cohesion)
class FeeCalculator {
int baseFee()
boolean shortage(Student s)
int fee(Student s)
}
(Outlines, not compilable code.) All four over-split classes change together whenever accounts changes the rule: that's one reason to change, scattered across four files. A responsibility is a reason to change, not a single method.
8. Cohesion revisited
| Too big | Just right | Too small |
|---|---|---|
| Many actors in one class (god class) | One actor, all of its rules | One actor spread over many classes |
In episode 10, cohesion meant how strongly a class's parts belong together. SRP makes that measurable: things belong together when the same actor asks for their changes.
Quick test: describe the class in one sentence, without the word "and".
FeeCalculatorcomputes a student's fee. One sentence, no "and".StudentRecordcomputes the fee and formats report cards and saves to the database: three "and"s, three actors.
The class diagram
Today's design:
«facade, temporary» StudentRecord
+ fee(): int
+ reportCard(): String
| |
v v
FeeCalculator ReportCardFormatter StudentRepository
+ fee(s: Student): int + format(s: Student) + save(s: Student, fee)
: : :
: (dashed: uses) : :
v v v
«record» Student
name, present, medical, total
| Element | Meaning |
|---|---|
StudentRecord (top) |
Temporary thin facade for old callers; associations (solid lines) to the classes it delegates to |
FeeCalculator, ReportCardFormatter, StudentRepository (middle) |
One class per actor: accounts, exam cell, IT team. Each has exactly one reason to change |
Student (bottom) |
Plain data (a record); all three depend on it (dashed arrows): they use it as a parameter |
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
int attendance() shared by fee() and reportCard() |
no error: Fee: Rs 50000 |
Two actors share one helper | One class per actor |
fee() / save() build SQL inside the business class |
no error: testing a fee needs a database | Logic mixed with persistence | A separate repository |
Moving fee() out in one big step |
error: cannot find symbol / symbol: method fee() |
Old callers still use the old API | A thin facade, then migrate |
| Merging two look-alike calculations | no error: one actor's change breaks another | Accidental duplication treated as real | Keep different actors' rules apart |
| One class per method | no error: one rule change edits four files | Over-splitting | Group by actor |
Mini project
Split the Invoice class from the quiz (the video's homework). total() and discount() follow tax rules (finance), toPdf() follows the invoice layout (design), emailToCustomer() follows mail server settings (IT). Rules: 10% discount when the subtotal is at least Rs 1,000; 18% tax on the amount after discount (whole rupees, rounded down). Make the invoice data a record, and write one class per actor. Test with items of Rs 800 and Rs 400.
Solution
import java.util.*;
record Invoice(String customer, String email, List<Integer> items) { }
class InvoiceCalculator { // actor: finance (tax rules)
int discount(Invoice inv) {
int sum = subtotal(inv);
return sum >= 1000 ? sum / 10 : 0;
}
int total(Invoice inv) {
int afterDiscount = subtotal(inv) - discount(inv);
return afterDiscount + afterDiscount * 18 / 100; // 18% tax
}
private int subtotal(Invoice inv) {
int s = 0;
for (int price : inv.items()) s += price;
return s;
}
}
class InvoicePdfFormatter { // actor: design (invoice layout)
String toPdf(Invoice inv, int total) {
return "[PDF] Invoice for " + inv.customer() + " | Total: Rs " + total;
}
}
class InvoiceMailer { // actor: IT (mail server settings)
void emailToCustomer(Invoice inv, String file) {
System.out.println("MAIL to " + inv.email() + ": " + file);
}
}
public class Main {
public static void main(String[] args) {
Invoice inv = new Invoice("Ravi", "ravi@example.com", List.of(800, 400));
InvoiceCalculator calc = new InvoiceCalculator();
int total = calc.total(inv);
System.out.println("Discount: Rs " + calc.discount(inv));
String pdf = new InvoicePdfFormatter().toPdf(inv, total);
System.out.println(pdf);
new InvoiceMailer().emailToCustomer(inv, pdf);
}
}
Output:
Discount: Rs 120
[PDF] Invoice for Ravi | Total: Rs 1274
MAIL to ravi@example.com: [PDF] Invoice for Ravi | Total: Rs 1274
Subtotal 1200, discount 120, after discount 1080, tax 194 (1080 x 18 / 100, rounded down), total 1274. Three actors, three classes: total and discount stay together because they belong to the same actor (finance). The "PDF" is a pretend string; a real one would use a PDF library, still inside the formatter.
Practice
- Write a test for
FeeCalculatorthat needs no database and no formatter (the homework). Check 60%, 75% and 90% attendance.
Solution
record Student(String name, int present, int medical, int total) { }
class FeeCalculator {
int fee(Student s) {
int pct = 100 * s.present() / s.total();
return 50000 + (pct < 75 ? 2000 : 0);
}
}
public class Main {
static void check(String what, int actual, int expected) {
System.out.println((actual == expected ? "PASS " : "FAIL ") + what + ": " + actual);
}
public static void main(String[] args) {
FeeCalculator calc = new FeeCalculator(); // no database, no formatter needed
check("60% present", calc.fee(new Student("A", 60, 20, 100)), 52000);
check("75% present", calc.fee(new Student("B", 75, 0, 100)), 50000);
check("90% present", calc.fee(new Student("C", 90, 0, 100)), 50000);
}
}
PASS 60% present: 52000
PASS 75% present: 50000
PASS 90% present: 50000
With the god class, the same test would have dragged in save() and its database. (Real projects use a testing library to run checks like these; the idea is the same.)
- Accounts adds a new rule: hostel students pay Rs 30,000 extra. Which class changes? Show it.
Solution
Only FeeCalculator, because the rule comes from the accounts office. The record gains a hostel field (data), and ReportCardFormatter doesn't change at all.
record Student(String name, int present, int medical, int total, boolean hostel) { }
class FeeCalculator { // the only class the accounts office's new rule touches
int fee(Student s) {
int pct = 100 * s.present() / s.total();
int fee = 50000 + (pct < 75 ? 2000 : 0);
if (s.hostel()) fee += 30000; // new rule: hostel fee
return fee;
}
}
class ReportCardFormatter { // unchanged
String format(Student s) {
int pct = 100 * (s.present() + s.medical()) / s.total();
return s.name() + ": attendance " + pct + "%";
}
}
public class Main {
public static void main(String[] args) {
Student ravi = new Student("Ravi", 60, 20, 100, true);
System.out.println(new ReportCardFormatter().format(ravi));
System.out.println("Fee: Rs " + new FeeCalculator().fee(ravi));
}
}
Ravi: attendance 80%
Fee: Rs 82000
- List the actors of this class and propose a split:
class Employee {
int calculatePay() // salary rules
String hoursReport() // the HR team's weekly report
void saveToDatabase() // database settings
}
Solution
Three actors: finance (pay rules), HR (report format), IT (database). Split into PayCalculator, HoursReportFormatter and EmployeeRepository, with an Employee record for the data. If calculatePay and hoursReport share a "regular hours" helper, give each class its own copy: it's accidental duplication.
- A teammate turns
FeeCalculatorintoBaseFeeProvider,ShortageChecker,FineAdderandFeeTotaller"to follow SRP". Is that right?
Solution
No. All four change for the same reason (an accounts office fee rule), so it's one responsibility scattered across four classes: low cohesion. SRP counts reasons to change (actors), not methods. Keep them in FeeCalculator.
- Use the "no and" test on: (a)
OrderService: "validates orders and charges the card and sends the confirmation email" (b)TaxCalculator: "computes the sales tax for an invoice".
Solution
(a) Two "and"s: three likely actors (business rules, payments, notifications). Split into OrderValidator, PaymentProcessor and OrderMailer, possibly behind a facade. (b) One sentence, no "and": one responsibility. Leave it.
Quick quiz
class Invoice {
int total() // tax rules
String toPdf() // invoice layout
void emailToCustomer() // mail server settings
int discount() // tax rules
}
How many reasons to change?
- 1
- 2
- 3
- 4
Answer
3. Three actors: finance (total, discount), design (toPdf), IT (emailToCustomer). Four methods, three responsibilities: split it into three classes, not four (see the Mini project).
Interview questions
- What is SOLID? Five class-design principles: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. Collected by Robert C. Martin (2000 paper "Design Principles and Design Patterns"); the acronym is from Michael Feathers, around 2004.
- State the Single Responsibility Principle. A class should have only one reason to change; in Martin's later wording, it should be responsible to one, and only one, actor.
- What is a "reason to change"? An actor? A reason to change is a source of change requests; an actor is the person or group making them (accounts office, exam cell, IT team).
- Does SRP mean one method per class? No. A class can have many methods if they all serve one actor. Over-splitting lowers cohesion.
- What is a god class, and how do you spot it? A class that knows and does everything: huge, growing, edited by many teams, hard to test, named Manager/Helper/Utils, and changes cause surprises.
- Why separate business logic, formatting and persistence? They change for different actors, at different times. Separate classes can be tested and changed alone (test fees without a database).
- What is accidental duplication? Code that looks the same but belongs to different actors. Merging it couples those actors; keep it apart.
- How do you refactor an SRP violation in a large code base? Group methods by actor, extract a class per group, split shared helpers, keep a thin facade so old callers compile, compare output after each step, migrate callers, delete the facade.
- How do SRP and cohesion relate? SRP is cohesion measured by actors: parts belong together when the same actor changes them.
- Give a quick SRP check. Describe the class in one sentence without "and".
Glossary
| Term | Meaning, with an example |
|---|---|
| Principle | A rule of thumb that tells you which designs tend to hurt later |
| Acronym | A word made from initials. SOLID |
| SOLID | Five class-design principles: S, O, L, I, D |
| Single Responsibility Principle (SRP) | A class should have one reason to change: be responsible to one actor |
| Responsibility | A job a class does for someone. Computing fees |
| Reason to change | A request that forces an edit to a class. "Count medical leave" |
| Actor | The person or group who makes change requests. Accounts office, exam cell, IT team |
| Module | A class or small unit of code changed together |
| Helper method | A small method other methods call. attendance() |
| SQL | The language for talking to databases. INSERT INTO students ... |
| Database | A program that stores data permanently |
| God class | A class that knows and does everything. StudentRecord, CollegeManager |
| Code smell | A pattern in code that hints at a design problem |
| Version control | A tool that tracks code changes and lets teams work together |
| Merge conflict | Two people changed the same lines; the tool can't combine them |
| Test | Code that runs code with known inputs and checks outputs |
| Business logic | The rules of the domain. Fees, fines, discounts |
| Formatting | Turning data into text or layouts for people. Report cards |
| Persistence | Storing data so it survives after the program ends |
| Separating persistence, formatting and business logic | The common SRP split: Repository, Formatter, Calculator |
| Repository | A class whose only job is saving and loading objects. StudentRepository |
| Record | A compact immutable data class. record Student(...) |
| Accidental duplication | Look-alike code owned by different actors; keep it apart |
| Machine-coding round | Interview round: write a working, well-designed program in limited time |
| Refactoring | Changing code's structure without changing behaviour |
| Big-bang refactor | Changing everything at once; old callers break together |
| Facade (thin facade) | A front class that keeps an old API and only delegates to new classes |
| API | The set of methods other code calls |
| Delegation | Handing work to an object you hold (episode 11) |
| Refactoring an SRP violation | Group by actor, extract classes, facade, compare output, migrate, delete facade |
| Over-splitting | One actor's rules scattered over many classes; not SRP |
| Cohesion | How strongly a class's parts belong together |
| Cohesion revisited | SRP's measure: parts belong together if the same actor changes them |
| "No and" test | Describe the class in one sentence without "and" |
Summary
- SOLID: five class-design principles (Martin, 2000; acronym by Feathers, around 2004). Today: S.
- SRP: one reason to change = one actor the class answers to.
- One shared helper across three actors let an exam cell change silently break the accounts office (Rs 52000 to Rs 50000).
- Watch for god classes; split business logic, formatting and persistence.
- Look-alike code with different owners is accidental duplication: keep it apart.
- Refactor in small steps behind a thin facade, comparing output each time.
- Over-splitting is low cohesion, not SRP. SRP is cohesion measured by actors: "no and".
Next episode: SOLID 2: The Open-Closed Principle: open for extension, closed for modification.