Decoding SOLID Principles (#2 Open/Closed)

Shubhi Puntambekar
2 min readMay 11, 2023

This a continuing series of the SOLID Principles. If you have not gone through the previous thread, I request you to check this post before continuing to read this one.

Open/Closed Principle

The open/close principle states that “Classes should be open for extension, but closed for modification.” This means that we can add new functionality to an existing class, but could not change the already written code (apart from fixing bugs in the existing code). This is because changing existing code can raise the risk of creating bugs in an already working system. Let’s understand this better with the help of the same example from the previous thread.

class Item:
def __init__(self, item, price, quantity):
self.item = item
self.price = price
self.quantity = quantity

class Invoice:
def __init__(self, items):
self.items = items

def calculate_total(self):
# do something to calculate total
pass

class InvoicePrinter:

def print_invoice(self):
# do something to print invoice
pass

class InvoiceDBHelper:

def save_to_db(self):
# do something to save to DB.
pass

So now, if we get a requirement that we need to store the invoice data in different places. For example, database and file. The current implementation doesn't allow us to add this functionality to the InvoiceDBHelper class. What we can do is either create a new class InvoiceFileHelper and write a function save_to_file() in it. But to create a better design we will do it as shown below.

# ....previous code

class Storage:
def save(self):
pass

class DatabaseStorage(Storage):
def save(self):
# save to DB
pass

class FileStorage(Storage):
def save(self):
# save to file
pass

Now what we have done in this code is that we have created a class Storage, which is implemented by DatabaseStorage and FileStorage class. So, in future, if we need to store the invoice in any other place, then we can simply create a new class and implement the save() function from the Storage class and modify it accordingly. This can also work in case we need to add another type of database.

Here we have followed the Open/Close principle. Now we don’t need to modify the existing code for adding new functionalities. We can just extend our code by creating new classes that implement the Storage class.

Continue reading about the Liskov Substitution Principle in the next thread by clicking here.

--

--