SOLID Principles: Open-Closed Principle (OCP)

Hussein Reda
2 min readOct 25, 2020


  • Software entities should be open for extension but closed for modification.
  • The OCP states that the behaviors of the system can be extended without having to modify its existing implementation.
  • New features should be implemented using the new code, but not by changing the existing code.
  • reduces the risk of breaking the existing implementation code.

if simple extensions to the requirements force massive changes to the software, then the architecture of that software is bad, and a good software architecture would reduce the amount of changed code to the barest minimum. Ideally, zero.

  • build the classes in a way that we able to extend them by child classes and inheritance and once you created the class, it no longer needs to be changed.
  • Example:
public enum paymentType = {Cash, CreditCard};public class PaymentManager{
public PaymentType paymentType {get;set;}
public void Pay(Money money){
if(paymentType =={
// pay with cash
// pay with credit card

and if we need to add a new payment type? we need to modify this class.

open for extension:

public class payment{public virtual void pay(Money money){// base class

close for modification:

public class CashPayment:payment{public override void pay(Money money){// pay with cash
}public class CreditCard:payment{public override void pay(Money money){// pay with credit card

Now if you need to add another payment logic you only need to create a new class and implement or extends the payment interface or base class.

If component A should be protected from changes in component B, then component B should depend on component A.


continuo to the rest of SOLID