# 🚀 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:

```javascript
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:

```javascript
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**:

```javascript
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***](https://kawaljain.medium.com/)
> 
> ***Follow me On*** [***Hashnode***](https://blog.kawaljain.com/)
> 
> ***Checkout more*** [***Portfolio***](http://kawaljain.com/)
> 
> ***Checkout more*** [Work](https://project.kawaljain.com/)
