SOLID Principles: Open-Closed Principle (OCP)

Image for post
Image for post
  • 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:

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

open for extension:

close for modification:

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.

OCP USE-CASE

continuo to the rest of SOLID

Written by

Software engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store