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
Dependency Inversion Principle
This principle suggests that below two points. a. High-level modules should not depend on low-level modules. Both should depend on abstractions. b. Abstractions should not depend on details. Details should depend on abstractions.
Violation of DIP
class BackendDeveloper:
"""This is a low-level module"""
@staticmethod
def python():
print("Writing Python code")class FrontendDeveloper:
"""This is a low-level module"""
@staticmethod
def javascript():
print("Writing JavaScript code")
class Project:
"""This is a high-level module"""
def __init__(self):
self.backend = BackendDeveloper()
self.frontend = FrontendDeveloper()
def develop(self):
self.backend.python()
self.frontend.javascript()
return "Develop codebase"
project = Project()
print(project.develop())
How does it violate the DIP?
The project class is a high-level module and backend & frontend are the low-level modules. In this example, we found that the high-level module depends on the low-level module. Hence this example are violated the Dependency Inversion Principle.
Solution
class BackendDeveloper:
"""This is a low-level module"""
def develop(self):
self.__python_code()
@staticmethod
def __python_code():
print("Writing Python code")
class FrontendDeveloper:
"""This is a low-level module"""
def develop(self):
self.__javascript()
@staticmethod
def __javascript():
print("Writing JavaScript code")
class Developers:
"""An Abstract module"""
def __init__(self):
self.backend = BackendDeveloper()
self.frontend = FrontendDeveloper()
def develop(self):
self.backend.develop()
self.frontend.develop()
class Project:
"""This is a high-level module"""
def __init__(self):
self.__developers = Developers()
def develops(self):
return self.__developers.develop()
project = Project()
print(project.develops())