Open closed
Lesson 23 of 28 in Coddy's Clean Code - Write better code using Python course.
"Software entities should be open for extension, but closed for modification."
The principle states that any function, module or class should allow extension of its behaviour without modifying the code itself.
Let's say we have class TxtConvertor which convert txt file to json or xml,
class TxtConvertor:
def convert_to_json(self, file):
print("converts file to json")
def convert_to_xml(self, file):
print("converts file to xml")This structure violates the Open-Closed principle.
Why?
For example if we want to add support for convertion from txt file to html we will have to modify the existing class (violates close principle)
So what should we do?
In this example one solution whould be to create abstract class which will hold the main function,
from abc import ABC, abstractmethod
class TxtConvertor(ABC):
@abstractmethod
def convert(self, file):
pass
class TxtConvertorToJson(TxtConvertor):
...
.
.
.
abclibrary supports abstract base classes for python you can read more here
Challenge
MediumYour task is to modify the given example to apply the Open-Closed princple , and add convertor to support txt to html.
- create abstract class
TxtConvertor - create classes
TxtConvertorToJson,TxtConvertorToXML,TxtConvertorToHTMLwhich will inherit fromTxtConvertorand implement the convertors (as in the example above)
Try it yourself
class TxtConvertor:
def convert_to_json(self, file):
print("converts file to json")
def convert_to_xml(self, file):
print("converts file to xml")