According to the book "Clean Code" by Robert C. Martin, the Single Responsibility Principle (SRP) is
Certainly! It's one of the fundamental principles of clean code design.
SRP states that a class should have only one reason to change, meaning it should have only one responsibility.
Here's an explanation and code example of SRP:
Explanation:
Imagine you have a class called User
that represents a user in a system. According to SRP, this class should have a single responsibility, which might be managing user data. However, if this class also handles user authentication and sends email notifications, it violates SRP because it has more than one reason to change.
In the context of SRP, "responsibility" means a reason to change. If you can think of more than one reason for a class to change, it's an indication that you should split it into multiple classes, each with a single responsibility.
Code Example:
Let's consider a simplified example in Java to illustrate SRP:
// A class representing a User with multiple responsibilities.
public class User {
private String username;
private String email;
public User(String username, String email) {
this.username = username;
this.email = email;
}
// Responsibility 1: Managing user data
public void saveUserToDatabase() {
// Database saving logic
}
// Responsibility 2: User authentication
public boolean authenticateUser(String password) {
// Authentication logic
return true; // Simplified for demonstration
}
// Responsibility 3: Sending email notifications
public void sendEmailNotification(String message) {
// Email sending logic
}
// ... Other methods related to various responsibilities
// Violation of SRP: This class has multiple reasons to change.
}
In this example, the User
class has three responsibilities: managing user data, user authentication, and sending email notifications. This violates SRP because a change in one responsibility might affect the others.
To adhere to SRP, you would split this class into separate classes, each with a single responsibility. For instance, you could have a UserRepository
class for managing user data, an Authenticator
class for user authentication, and an EmailSender
class for sending email notifications. This separation would make your code more maintainable and less prone to unexpected side effects when you need to make changes.
Adhering SRP ensures that each class has a clear responsibility and helps create
cleaner
more maintainable and
less error-prone code