Definition:
A class should have only one reason to change, meaning it should have only one job or responsibility.
Explanation:
The Single Responsibility Principle emphasizes that a class should focus on a single task or functionality. By adhering to SRP, developers ensure high cohesion within classes, making the system easier to understand, maintain, and modify. When a class has multiple responsibilities, changes related to one responsibility can inadvertently affect others, leading to a fragile and error-prone codebase.
Example:
Consider a User class that handles user data as well as user authentication. According to SRP, these responsibilities should be separated into distinct classes:
# Violates SRP
class User:
def __init__(self, username, password):
self.username = username
self.password = password
def authenticate(self):
# Authentication logic
pass
# Adheres to SRP
class User:
def __init__(self, username, password):
self.username = username
self.password = password
class Authenticator:
def authenticate(self, user):
# Authentication logic
pass