
In my previous articles I wrote about Solid Principles in C# and the Single Responsibility Principle.
In this article, I am going to show you when and how to use the Open Closed Principle in C# with an example project. You can find the repository on GitHub.
The master branch shows the initial code used in the example. There are separate tags and branches for each of the all solid principles that you can review or download as well. Here are links you can use to jump to these tagged versions in your browser:
What is the Open Closed Principle (OCP) in C#?
The Open Closed Principle is one of the SOLID design principles. We can always reuse the definition from Wikipedia.
The Open Closed Principle states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
So these software entities should be:
- Open For Extension This means that the behavior of the module can be extended, for example we could add fields or new elements in the functions with a fixed behavior,
- Closed for Modification The source code of such a module is inviolate. No one is allowed to make source code changes to it.
Why should you use the Open Closed Principle (OCP)?
- Application robust. Don’t break existing code, prefer implementing new features in new classes, follow the SRP, no need to change tested class and less bug.
- Flexible. Working with interfaces, it’s easy to accommodate new requirements and this reduces the cost of a business change requirement.
- Better testability. Easy to test and less error prone.