Member-only story

SOLID design principles: Open Closed Principle

Trisha
1 min readSep 5, 2024

--

S.O.L.I.D principles define ways to write code such that the code

  • avoids duplicate code
  • easy to maintain
  • easy to understand
  • reduce complexity
  • increase flexibility.

Open/ Closed Principle:

Open for extension but closed for modification

Assume the uploadTransactionToCloud uploads the transaction as pdf and you want to have another way for uploading say csv files. How can you do that. One way to do it would be adding another function to the PersistInvoice class.

class PersistInvoice:
def __init__(self, invoice: Invoice):
self.invoice = invoice
def uploadTransactionAsPDF(self):
// upload transactions to cloud as PDF
def uploadTransactionAsCSV(self):
// upload transactions to cloud as CSV

However this violates the Open/Close Principle.

Instead, one can create an Interface for the PrintInvoice and extend it to classes which provide various functionalities. This way we have only one change for each class from Single Responsibility Principle and adding new methods of printing does not disrupt old printing classes.

from abc import ABC…

--

--

No responses yet