Liskov Substitution Principle or: Don’t Use The One Thing Stroustrup Actually Didn’t Want in C++ Anyway
I’m starting to think Uncle Bob likes inheritance. The Liskov Substitution Principle takes a computer science paper about subtyping, and, over 11 pages, tells us not to look at the type of objects at run-time or bad things will happen.
I’m inclined to just stop here, because in what world is this such a problem that it needs a principle to help us avoid?
That said, I do need to bail out Barbara Liskov, whose name got attached to this principle. Unlike us programmers, Barbara Liskov is a legit computer scientist. She does real research, writes real papers, and won the Turing Award! We owe it to her to explain how her name got on this, because she did not win the Turing Award for this principle.
Papers We Love But Have Not Really Read
Barbara Liskov and Jeannette Wing authored a paper that explores the definition of subtypes as it related to program correctness. They state that if an object y has all the properties of object x, then we can safely use y anywhere we use x and that y is a subtype of x. If y does not have all the properties of x, it is not a subtype of x.
Most programming languages implement a somewhat…looser definition of subtyping. Java, for example, allows any object y to be used in place of any object x so long as y’s class inherits (directly or transitively) from x’s, or if x and y implement the same interface. In Ruby, pass whatever to whatever, it’s cool, don’t worry about it, we have duck typing and if it quacks like a monkey with a duck taped to its stomach then everything will work fine until Rails 6.2 which deprecates taping, but you can install the rails-duck-taping gem to get that feature back.
So what does this have to do with object-oriented design? Not much.
Buy now to keep reading