Skip to main content
4 of 17
added 261 characters in body
nicholaswmin
  • 2.1k
  • 2
  • 21
  • 38

For the same reason you avoid inheritance in non-dynamic languages.

Inheritance is the strongest coupling relationship. Often times too strong, inflexibly so.

What you're expressing is that the child class must have an is-a relationship with the parent.

Otherwise it violates the Liskov Principle.

My incomplete but practical 2-liner is this:

The child should be perfectly substitutable with it's > parent, with no change in behaviour; meaning no errors and > no incorrect-behaviour in either.

This isn't an abstract rule, it has practical repercussions:

If Class A has an is-a relationship with Class B, you, or (most likely) another person that got convinced by your is-a assertion` of that relationship will be tempted to write something like this:

class Mammal {  
  move() { 
    this.backLegs.move()
  }
}

class Dog extends Mammal {
  move() {
    super.move()
    this.moveFrontLegs()
  }
}

class Whale extends Mammal {     
  move() { 
    super.move()
    this.moveFins()
  }
}

const items = [new Plant(), new Table(), new Car(), new Dog(), new Fish()]

// we want to move just the animals:
items.
  // ok they are animals, 
  // and we know all of them can move
 .filter(item => item instanceof Animal)
 .forEach(animal => animal.move())


// whale is moving it's back legs ???
nicholaswmin
  • 2.1k
  • 2
  • 21
  • 38