0
0
LLDsystem_design~3 mins

Why Open/Closed Principle in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new features without ever breaking your existing app?

The Scenario

Imagine you built a simple app that calculates discounts for products. Every time a new discount rule comes up, you open the existing code and change it directly.

At first, it works fine. But soon, the code becomes a tangled mess of if-else checks, and every change risks breaking something else.

The Problem

Changing the same code repeatedly is slow and risky. You might accidentally break existing features. Testing becomes harder because changes affect many parts. It's like fixing a leaky pipe by patching holes everywhere instead of replacing the pipe.

The Solution

The Open/Closed Principle says: design your system so it is open for extension but closed for modification. This means you add new features by adding new code, not by changing old code. Your original code stays safe and stable.

This keeps your system flexible and easier to maintain as it grows.

Before vs After
Before
if (discountType == 'seasonal') { applySeasonalDiscount(); } else if (discountType == 'clearance') { applyClearanceDiscount(); }
After
class Discount { apply() {} } class SeasonalDiscount extends Discount { apply() { /* seasonal logic */ } } class ClearanceDiscount extends Discount { apply() { /* clearance logic */ } }
What It Enables

You can add new features without fear of breaking existing code, making your system more reliable and easier to grow.

Real Life Example

Think of a music player app that supports new audio formats. Instead of rewriting the player each time, it adds new format handlers separately, keeping the core player stable.

Key Takeaways

Changing existing code often leads to bugs and slow progress.

Open/Closed Principle encourages adding new code instead of changing old code.

This approach makes software easier to maintain and extend.