This article was done using my notes from Vubon Roy & Deekey (2019).
Vubon Roy, (Nov 2, 2019), SOLID Principles with Python Examples, Medium. Deekey, (Aug 2, 2019),S.O.L.I.D Principles explained in Python with examples.s, Medium. Wikipedia, (2020), Robert C. Martin.
SOLID principles
SOLID principles are designed to guide Object Oriented Programing. The SOLID principles were defined in the early 2000s by Robert C. Martin.
SOLID stands for
1. Single Responsibility Principle
2. Open and Closed Principle
3. Lisvok Sub situation Principle
4. Interface Segregation Principle
5. Dependency Inversion Principle
Single Responsibility Principle
A class should have only one responsibility and only one reason to change. That means a class does not perform multiple jobs.
Violation of SRP
class User:
"""Demo User class"""
def __init__(self, name: str):
self.name = name
def get_name(self):
"""Get User name"""
return self.name
def save(self):
"""Save user to DB"""
pass
How does it violate the SRP?
In the User class, I am performing two tasks. One is stored data and another one gets the user’s name. So it violates the SRP.
Solution
So we simply split the class, we create another class that will handle the one responsibility of storing an user to a database
class User:
def __init__(self, name):
self.name = name
def get_name(self):
pass
class UserManager:
def get_user(self, id):
pass
def save(self, user: User):
pass