Single Responsibility Principle (SRP)
1. Introduction
The Single Responsibility Principle is one of the five SOLID principles of object-oriented design. It states that a class should have only one reason to change, meaning it should have only one job or responsibility.
2. Definition
Single Responsibility Principle (SRP): A class should have one and only one reason to change. This means that a class should only have one responsibility or job.
3. Importance
- Enhances code readability and maintainability.
- Reduces the impact of changes.
- Improves testability of the code.
- Facilitates better separation of concerns.
4. Code Examples
4.1 Bad Example
class User {
public function createUser($data) {
// Logic to create user
}
public function sendEmail($email) {
// Logic to send email
}
public function logUserActivity($activity) {
// Logic to log user activity
}
}
In this example, the User
class has multiple responsibilities: creating a user, sending an email, and logging activity.
4.2 Good Example
class User {
public function createUser($data) {
// Logic to create user
}
}
class EmailService {
public function sendEmail($email) {
// Logic to send email
}
}
class ActivityLogger {
public function logUserActivity($activity) {
// Logic to log user activity
}
}
Here, each class has a single responsibility. The User
class only handles user creation, EmailService
handles email, and ActivityLogger
manages logging.
5. Best Practices
- Identify responsibilities in your classes and separate them.
- Refactor classes that have multiple reasons to change.
- Use interfaces to define single responsibilities.
- Consider using dependency injection to manage dependencies effectively.
6. FAQ
What happens if I don't follow SRP?
If SRP is not followed, classes can become bloated and difficult to maintain. Changes in one responsibility may inadvertently affect others.
How do I identify responsibilities in a class?
Look for methods that perform distinct actions or operations that can evolve independently. Each should ideally belong to a separate class.
Can SRP be applied to functions or modules?
Yes! SRP can and should be applied at all levels of your application, including functions and modules, to enhance clarity and maintainability.