Single Responsibility Principle (SRP)

🧠 What is the Single Responsibility Principle (SRP)?
The Single Responsibility Principle says:
A class (or method) should have only one reason to change.
In plain English:
A class should do only one thing
A method should do only one action
Keep it focused and clean
🏡 Real-World Analogy: Building a House
🚫 Bad Example: One Person Doing It All
Imagine this:
You're building a house. One guy comes in and says:
“Don’t worry! I’ll do the plumbing, electrical, architecture, painting, and interior design!”
That’s a disaster waiting to happen.
Now apply this to code:
public class House {
void buildFoundation() { /* ... */ }
void paintWalls() { /* ... */ }
void installElectricity() { /* ... */ }
void layPipes() { /* ... */ }
void designInterior() { /* ... */ }
}
This class has too many responsibilities. If you want to change the interior layout, you might break the plumbing. Not good.
✅ Good Example: Each Class Has One Job
Just like a real house project has:
A Plumber
An Electrician
A Painter
An Architect
We split our Java classes too:
public class FoundationBuilder {
void buildFoundation() { /* logic */ }
}
public class Painter {
void paintWalls() { /* logic */ }
}
public class Electrician {
void installElectricity() { /* logic */ }
}
Now each class has one reason to change. If someone changes how painting works, they don't mess up the wiring.
🎯 What About Methods?
🚫 Bad Method Example (Too Many Jobs)
void buildHouse() {
buildFoundation();
paintWalls();
installElectricity();
designInterior();
}
It’s like a meeting that tries to solve every problem at once — confusing!
✅ Good Method Example (One Action per Method)
void buildFoundation() { /* ... */ }
void paintWalls() { /* ... */ }
void installElectricity() { /* ... */ }
Now each method does one job, is easier to test, and less likely to break.
🔁 Real-World Mapping
Real House Role | Java Equivalent |
Plumber | PlumbingService class |
Electrician | ElectricalService class |
Interior Designer | InteriorService class |
Architect | BlueprintDesigner class |
Paint job | paintWalls() method |
✍️ Final Takeaway
Code like you're hiring workers to build your house.
Don't hire one person to do it all.
📢 Bonus Developer Tip
✅ Smaller classes = Better code.
✅ Easier to test, reuse, debug, and maintain.
“SRP is not about splitting everything — it’s about grouping code by what changes together*.”*
Subscribe to my newsletter
Read articles from bharath chandanala directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
