L jak Liskov Substitution Principle

By Karol Bocian | February 21, 2020

Liskov Substitution Principle

The application should work correctly when we put in the base class place every derived class. There is required full interface and method compatibility. You should remember, during designing class hierarchy, that every class can use their method from base class without overriding them. Methods of derivative classes should at most extend base method (can call them in their implementation).

This rule can be applied to methods, functions, classes, modules and packages.

Advantages

  • More readable code.
  • More understandable code.
  • Fewer surprises in code.
  • Easier maintenance.
  • Possibility to substitute base class by any derivative class with sure, that the program works fine.
  • Fewer dependencies in code — handling list of objects do not require checking of this object type and handling in a specific way.

Disadvantages

  • The need to think better about class structure and inheritance.

Examples

  • Square inherits from Rectangle — AreaCount needs to be overridden in Square class.
  • Fish inherits from Animal, where Animal has method Run. Fish do not run of course!
  • Classes FileReadonly and FileWriteAndRead inherit from File. Class File has method Read and Write. In FileReadonly method Read is… confusing.

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials