Menu
Coddy logo textTech

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):
	...

.
.
.

abc library supports abstract base classes for python you can read more here

challenge icon

Challenge

Medium

Your task is to modify the given example to apply the Open-Closed princple , and add convertor to support txt to html.

  1. create abstract class TxtConvertor
  2. create classes TxtConvertorToJson, TxtConvertorToXML, TxtConvertorToHTML which will inherit from TxtConvertor and 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")

All lessons in Clean Code - Write better code using Python