Sunday, October 16, 2016

Liskov Substitution Principle

If it looks like a duck, quacks like a duck, but needs batteries, you probably have the wrong abstraction.

Or, in sciency talk:

“The Liskov Substitution Principle says that the object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class.

“In short: if S is subset of T, an object of T could be replaced by object of S without impacting the program and bringing any error in the system. Let’s say you have a class Rectangle and another class Square. Square is as Rectangle, or in other words, it inherits the Rectangle class. So as the Liskov Substitution principle states, we should able to replace object of Rectangle by the object of Square without bringing any undesirable change or error in the system.”

(The duck/battery example makes more sense. Makes sense. Maybe. However, if the alleged duck needs batteries, how is one to know it quacks? Or is there an assumption someone has heard the alleged duck quack? Doesn't the hearing then override the stated "you probably have the wrong abstraction"?)

No comments:

Post a Comment