SOLID Principles: Open/Closed Principle
Hello Everyone!
POST-5 of the series Introduction to software design principles and patterns.
Today’s topic is “SOLID Principles: Open/Closed Principle”.
Open/Closed Principle states that classes should be open for extension but closed for modification. The main idea behind this principle is to add new feature without breaking existing working code.
To explain this in detail, let’s look at “Order class” in diagram below. It has one method “processPayment” which processes payment depending on payment type. Initially we have 2 payment type- Credit and debit. Now we want to add third payment type UPI. To do that in processPayment, we need to add one more if condition and add logic for UPI payment. Doing this violates Open/Closed principle as we are modifying the existing code.
To avoid this scenario, while designing Order class we should have created different PaymentProcessor like “CreditPaymentProcessor” and “DebitPaymentProcessor”. Now if we want to add another payment processor, we just need to create respective payment processor class. Thus making it easier to add multiple payment processors.
Get Niraj Markandey’s stories in your inbox
Join Medium for free to get updates from this writer.
One more way to extend functionality is by creating subclass and adding functionality there.
The main benefit of open/closed principle is as bellow
- avoid side effects from adding new features
- improves maintainability
- Adds flexibility to design
Next Topic in this series will be “SOLID Principles: Liskov Substitution Principle”.
Previous post “SOLID Principles: Single Responsibility Principle”








