OCP: Open-Closed Principle

Hicham BEN KACHOUD
2 min readMar 31, 2022

--

Introduction

The Open Closed Principle is one of 5 principles of Object-Oriented Design. They are :

In this post, I will focus on OCP, and I will explain the other principles in future articles.

Definition

Uncle Bob defines the principle as:

Entities (classes, functions, …) should be open for extension, but closed for modification.

The main idea behind this principle is to avoid creating bugs on existing code when adding new functionalities.

When you have an entity that is developed, tested and validated in your application, modify this entity is so risky. Perhaps you can add a sub-class and change the parent functionality needed using Polymorphism. Or you can also achieve the OCP using Inheritance or the Strategy design pattern.

Example

Imagine we have a scenario where there is a project that consist in an intranet that allows to calculate the sup hours amount of the company’s employees.

Our application calculate the sup hours amount based on employe’s type: Manager and Regular.

Bad Implementation

In this example, we have an Employee class that manages both types: Manager and Regular. The application works perfectly but, you received another requirement to add a new type of employee: Supervisor.

Adding new type, you must change the calculateSupHours method which is bad, if each time we have new type.

Implementing OCP

There are many solutions to implement the OCP, and here I will show a simple one using the inheritance.

So look at the following code:

Good Implenetation
  • Make the Employee class abstract and the calculateSupHours function too.
  • Add two classes that extend the Employee class and implement the calculateSupHours behviour.

The code now is clear and easier to test and extend in the future.

Now it is easy to add the Supervisor type: You should add the Supervisor Class and extend the Employee class.

Conclusion

The OCP promotes the use of new sub-classes or interface to adapt the functionality without changing the existing code.

Thank you for reading this quick post. If you like the content feel free to follow me on my social media profiles. Thank you.

Twitter: https://twitter.com/HBenkachoud
Linkedin: https://www.linkedin.com/in/hicham-benkachoud/

--

--

Hicham BEN KACHOUD
Hicham BEN KACHOUD

No responses yet