What is "S" in SOLID?
The Single Responsibility Principle (SRP) is one of the five SOLID principles of object-oriented programming and design, advocated by Robert C. Martin. The principle states that a class should have only one reason to change, meaning it should have only one job or responsibility. Here's a breakdown of what this means:
In practice, SRP is about finding the right level of abstraction and keeping components of the software as independent as possible. It's not always about having classes that do extremely narrow tasks, but rather ensuring that each class is only concerned with a single aspect of the system's functionality.
Without SRP
Imagine we have a class in a hypothetical programming language that manages user information and also handles the user's login process. This class violates SRP because it has more than one reason to change (managing user information and handling authentication).
Recommended by LinkedIn
class UserManagement:
def __init__(self, user):
self.user = user
def updateUserDetails(self, newDetails):
# Update user details like name, email, etc.
pass
def login(self, username, password):
# Handle the login process
pass
def logout(self):
# Handle the logout process
pass
In this example, UserManagement has responsibilities for both user details management and authentication (login/logout). If we need to change how user details are updated or how login works, we risk impacting the other functionality.
Refactored Example with SRP
To adhere to SRP, we can split this class into two separate classes: one for managing user details and another for handling the authentication process.
class UserDetails:
def __init__(self, user):
self.user = user
def updateUserDetails(self, newDetails):
# Update user details like name, email, etc.
pass
class UserAuthentication:
def __init__(self, user):
self.user = user
def login(self, username, password):
# Handle the login process
pass
def logout(self):
# Handle the logout process
pass
Now, we have two classes:
This refactoring makes the code more maintainable and less prone to bugs related to unrelated functionalities affecting each other. Each class has a single responsibility, aligning with the Single Responsibility Principle.