Liskov Substitution Principle

TopicSource
๐Ÿงน Clean CodeClean Code - Udemy

Objects should be replaceable with instances of their subclasses without altering the behavior.

This means, that you should be able to use a subclass instead of the main class and everything should still work.

class Bird {}
  fly() {
    console.log('Fyling...');
  }
}

class Eagle extends Bird {
  dive() {
    console.log('Diving...');
  }
}

// this is fine
const eagle = new Bird();
eagle.fly();
// and this is fine, you can replace the bird with the eagle
const eagle2 = new Eagle();
eagle2.fly();
);

// this is not right
class Penguin extends Bird {
  // Problem: Can't fly!
}

This example shows, that you need a different parent class to fulfill the Liskov Substitution Principle:

class Bird {}

class FlyingBird extends Bird {
  fly() {
    console.log('Fyling...');
  }
}

class Eagle extends FlyingBird {
  dive() {
    console.log('Diving...');
  }
}

const eagle = new Eagle();
eagle.fly();
eagle.dive();

class Penguin extends Bird {
}

This ensures, that you can replace Bird with Eagle, without breaking when you replace Bird with Penguin.


  1. Law of Demeter - Don't depend on strangers
  2. Functions should be small and do one thing - they should have a single responsibility
  3. Open Closed Principle