Single Responsibility Principle: Definition and Practical Guide
Single Responsibility Principle means a class or module should have only one reason to change, focusing on a single job or responsibility. This keeps code simple, easier to maintain, and less prone to bugs.How It Works
Imagine a Swiss Army knife that tries to do everything: cut, screw, open bottles, and more. If one tool breaks, you might have to fix the whole knife. The Single Responsibility Principle (SRP) says each tool should be separate, so fixing one doesn't affect the others.
In software, this means each class or module should handle only one part of the program's functionality. If you need to change something, you only update the part responsible for that task. This makes the system easier to understand and safer to modify.
Example
This example shows a class that violates SRP by handling both user data and sending emails. Then it is split into two classes, each with a single responsibility.
class User { constructor(name, email) { this.name = name; this.email = email; } save() { console.log(`Saving user ${this.name} to database.`); } sendWelcomeEmail() { console.log(`Sending welcome email to ${this.email}.`); } } // Violates SRP: User class does two jobs class UserSRP { constructor(name, email) { this.name = name; this.email = email; } save() { console.log(`Saving user ${this.name} to database.`); } } class EmailService { sendWelcomeEmail(user) { console.log(`Sending welcome email to ${user.email}.`); } } // Usage const user = new UserSRP('Alice', 'alice@example.com'); user.save(); const emailService = new EmailService(); emailService.sendWelcomeEmail(user);
When to Use
Use the Single Responsibility Principle whenever you design classes or modules. It is especially helpful in large projects where many people work on the same code. It helps avoid bugs caused by unrelated changes.
For example, in a shopping app, separate classes can handle payment processing, order management, and notifications. This way, changing how payments work won't affect order logic or notifications.
Key Points
- Each class or module should have one clear responsibility.
- Changes in one responsibility should not affect others.
- Improves code readability and maintainability.
- Reduces bugs by isolating changes.