03 / 11

How would you model a Bird class? What issues arise when you try to add a Penguin or Ostrich? (LSP violation)

Difficulty: 4/10

Avoiding Incorrect Inheritance with Capability-Based Modeling

A common modeling mistake is to define Bird with a Fly() method and then derive Penguin and Ostrich from Bird. Penguins and ostriches are birds biologically but cannot satisfy a behavioral contract that requires flying. This can violate the Liskov Substitution Principle because code expecting any Bird to fly would fail for those subclasses. I would separate common bird identity from capabilities such as flying.

javascript
  1. 1

    The problem is not that Penguin is not a Bird; it is that Bird has been given an inappropriate behavioral contract.

  2. 2

    Separate capabilities from identity when capabilities are not universal.

  3. 3

    Interfaces such as IFlyingBird can model optional capabilities.

  4. 4

    LSP requires derived types to honor the behavioral expectations of their base abstraction.

  5. 5

    Avoid methods that derived classes must implement by throwing NotSupportedException merely to satisfy inheritance.

Follow-up Questions

  • What exactly is violated in the traditional Bird-Fly model?
  • How does ISP help solve this problem?
  • Can inheritance still be used for Bird?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.