Single Responsibility Principle: A class should only have one reason to change. Here is an example of a class that violates the Single Responsibility Principle by combining two unrelated responsibilities:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def pay_salary(self):
# pay employee's salary
pass
def send_email(self, message):
# send email to employee
pass
The Employee class has two responsibilities: paying the employees salary and sending an email to the employee.
If the Employee class is changed in any way, it will likely affect both responsibilities.
If the Employee class is changed to pay the employees salary,
it will likely affect the send_email method. If the Employee class is changed
to send an email to the employee, it will likely affect the pay_salary method.
The Employee class violates the Single Responsibility Principle
because it has two reasons to change. The Employee class should be split into two classes:
one class to pay the employees salary and another class to send an email to the employee.
To adhere to the Single Responsibility Principle, we can split the responsibilities
of the Employee class into two separate classes:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class SalaryPaymentService:
def pay_salary(self, employee):
# pay employee's salary
pass
class EmailService:
def send_email(self, employee, message):
# send email to employee
pass