When writing code, it’s common to put multiple responsibilities inside a single file or function. It might work at first, but over time it becomes difficult to manage and update.
The Single Responsibility Principle (SRP) helps solve this.
It is one of the core ideas from SOLID and focuses on keeping code simple and maintainable.
What is Single Responsibility Principle?
The idea is simple:
A class or function should have only one responsibility.
That means:
- It should do one job
- It should have one reason to change
Why This Matters
When a class does too many things:
- Changes become risky
- Bugs become harder to track
- Code becomes difficult to understand
Keeping responsibilities separate makes your code:
- Cleaner
- Easier to maintain
- Easier to scale
Bad Example (Multiple Responsibilities)
Let’s say we have a function like this:
function processUserData(user) {
// validate user
if (!user.email) {
console.log("Invalid user");
return;
}
// save user
console.log("Saving user to database");
// send email
console.log("Sending welcome email");
}
Problem here:
- Validation
- Saving data
- Sending email
If something changes (like email logic), you must modify this function.
Good Example (Single Responsibility)
Now let’s split the responsibilities:
function validateUser(user) {
return user.email ? true : false;
}
function saveUser(user) {
console.log("Saving user to database");
}
function sendEmail(user) {
console.log("Sending welcome email");
}
Now use them:
function processUser(user) {
if (!validateUser(user)) return;
saveUser(user);
sendEmail(user);
}
Why this is better:
- Each function does one job
- Easy to update or replace any part
- Code becomes reusable
Real-Life Analogy
Think of a restaurant:
- Chef – cooks food
- Cashier – handles billing
- Delivery – delivers food
If one person does everything, it becomes messy.
Key Idea to Remember
- Doing one thing
- Doing it well
- Keeping things separate
Conclusion
At the beginning, combining everything in one place might feel faster. But as your project grows, it creates problems.
By following SRP, your code becomes:
- Easier to read
- Easier to modify
- More organized
Comments
Post a Comment