🚀 SOLID Principles Series – Part 2: Open/Closed Principle (OCP)

Kawal JainKawal Jain
2 min read

Open/Closed Principle (OCP)

Make your code ready for change — without breaking old stuff

“A class should be open for extension but closed for modification.”
— Bertrand Meyer


What Does That Even Mean?

Let’s break it down:

  • Open for extension = You can add new things to it (new features, types, logic).

  • Closed for modification = You don’t change old working code that’s already been tested.

So basically:

You should be able to add new features without editing old code.


A Real-Life Example

Imagine you built a school prize system:

function getPrize(category) {
  if (category === 'sports') return 'Trophy';
  if (category === 'science') return 'Medal';
  if (category === 'music') return 'Certificate';
}

Now you want to add "Art" as a new category.

What do you have to do?

You’ll go inside the getPrize() function and change it — but that might accidentally break the others!


Let’s Follow the Rule

We’ll make a system in which each category has its own logic:

class Prize {
  getPrize() {
    return 'No prize';
  }
}

class SportsPrize extends Prize {
  getPrize() {
    return 'Trophy';
  }
}

class SciencePrize extends Prize {
  getPrize() {
    return 'Medal';
  }
}

class MusicPrize extends Prize {
  getPrize() {
    return 'Certificate';
  }
}

Now to add Art:

class ArtPrize extends Prize {
  getPrize() {
    return 'Sketchbook';
  }
}
  • No changes to old classes.

  • We just extended the system by adding a new class.

That’s the Open/Closed Principle!


Why Should You Care?

  • Adding new feature is easier

  • Easily maintainable when project will grow.

  • You don’t need to worry about the old code


Final Thoughts

The Open/Closed Principle is like building with LEGO:

  • You don’t break the old code.

  • You just add new code!

The Liskov Substitution Principle—what happens when classes don't behave as we expect them to—will be covered in the upcoming post.


Let’s Keep Building Together

I hope you enjoyed this..! Feel free to share your thoughts, questions, or ideas for future topics in the comments.

Thanks for reading

Happy coding!

If you enjoyed the article and would like to show your support, be sure to:

Follow me On Medium

Follow me On Hashnode

Checkout more Portfolio

Checkout more Work

0
Subscribe to my newsletter

Read articles from Kawal Jain directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kawal Jain
Kawal Jain

🧑‍💻 Full Stack Developer | JavaScript & GenAI Enthusiast 🚀 7+ years building scalable web apps with React, Node.js & PHP 💡 Exploring GenAI, Microservices, and Clean Code Principles 📚 Blogging my dev journey, lessons learned, and side experiments ♟️ Chess lover | Vegetarian foodie | Life-long learner