0
0
LLDsystem_design~3 mins

Why Liskov Substitution Principle in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if every part you swapped just worked perfectly without surprises?

The Scenario

Imagine you have a family of remote controls for different devices. You try to use a remote control designed for a TV to operate a DVD player, but it doesn't work as expected because the buttons behave differently.

The Problem

When you manually swap parts or components without ensuring they behave the same way, your system breaks. This causes confusion, errors, and extra work to fix unexpected behaviors.

The Solution

The Liskov Substitution Principle ensures that any component or class can be replaced by its subtype without changing the correctness of the program. This means you can swap parts freely, and everything still works smoothly.

Before vs After
Before
class TVRemote {
  void pressPlay() { /* plays TV channel */ }
}

class DVDRemote extends TVRemote {
  void pressPlay() { throw Exception('Not supported'); }
}
After
interface Remote {
  void pressPlay();
}

class TVRemote implements Remote {
  void pressPlay() { /* plays TV channel */ }
}

class DVDRemote implements Remote {
  void pressPlay() { /* plays DVD */ }
}
What It Enables

It enables building flexible systems where components can be swapped or extended without breaking existing functionality.

Real Life Example

Think of a universal charger that works with any phone brand without causing damage or malfunction.

Key Takeaways

Ensures subtypes can replace base types without errors.

Prevents unexpected behavior when swapping components.

Supports flexible and maintainable system design.