Open Closed Principle (OCP) – S.O.L.I.D. Framework

The second principle of the S.O.L.I.D. Framework is the Open Closed Principle (OCP). At the very first moment the combination of open and closed at the same time creates some confusion, but after we dig deeper it makes sense.

The main statement of this principle is “A software module is open for extension and closed for modification“.

So, at writing software we should make sure that an class/module is open for extension but closed for any modifications/changes. Of course there is one exception – bug fixing :-).

If we take a look at the example from the first principle (SRP) and we want to add a method to the AccountManager class – e.g. Unregister, we usually would add this method directly under the Register method, but this would violate the OCP!

Instead we can use inheritance to match the OCP defintion. Our extended program would somehow look like this:

This is one way to be compliant to the OCP and therefore the S.O.L.I.D. Framework.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.