Skip to main content

Command Palette

Search for a command to run...

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

Keep Your Code Flexible — Add New Stuff Without Messing Up Old Logic

Updated
•2 min read
🚀 SOLID Principles Series – Part 2: Open/Closed Principle (OCP)

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

SOLID for Starters – Write Better Code, One Principle at a Time

Part 1 of 2

This series is an easy-to-follow manual for learning and using JavaScript's SOLID principles of object-oriented programming. This series will help you understand powerful design concepts one principle at a time.

Up next

🚀 SOLID Principles Series – Part 1: Single Responsibility Principle (SRP)

One class. One job. One reason to change