What is the Open-Closed Principle?

Md Shakib Uddin Bhuiyan
2 min readAug 11, 2021

Photo by Tim Mossholder on Unsplash

Today we will see the “O” part of the SOLID principle, The Open-Closed Principle.

It states that “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”.

Confused?

Photo by Tim Gouw on Unsplash

It’s simple actually. It says that you don’t have to modify your old code when you add new code. That’s all!

Still, confused?

Let’s see an example.

Suppose, your boss told you to write a program that can post jobs. And you wrote something like this.

This code violates the Open-Closed Principle.

Why?

What if you wanted to add a Full Stack Developer job?

You would have to modify the postJob function by adding another else-if condition, that checks jobs from the array you passed. And add a new object in the jobs array.

But the Open-Closed Principle says.

Your code should be open for extensions and closed for modifications.

What happens when you have to add 10 more jobs? You will have to add 10 more else-if conditions and 10 more objects in the jobs array. Things will get messy. You will create a lot of unintentional bugs and get irrelevant CVs from irrelevant candidates. Your boss might fire you and hire someone from the candidates to write the program properly this time!

So, How can we improve this code?

See the code below.

This code follows the Open-Closed Principle.

You can add hundreds of different jobs and you would never have to touch the postJob function or the Job class at all. All you have to do is add jobs in the jobs array. If you have a job that has more features than your Job class, you can add a child class that extends the Job class or even create a new one and add the object in the jobs array. That’s it, The new code is an extension, not a modification of old codes. The postJob function and the Job class are closed for modification but your code is open for extension. Add whatever job you want, your code will work automatically.

That’s Open Closed Principle.

Give a clap if you liked this, and don’t forget to share it with your friends so that they don’t get fired.

Hey, If you haven’t read the first Principle in the SOLID series yet, you can visit this link.

My other writings,

Super in Java

Inheritance

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response