What is the Liskov substitution principle? (Part 1)
Explanation by analogy
Wanting protection from armed bandits (and politicians), I decided to arm myself. So I walked into my local corner-store Baton Rouge gun dealership and demanded:
“Pray, kind sir, I wish to procure a Colt Walker – and have come hence for that purpose. Will not, my estimable colleague thus oblige me?”
He looked at me a little perplexed, as he replied:
“Colt Walkers: dem’s a little ol’ fashioned. More than 150 years old. That’s the great grand-daddy of grand-daddies. You don’t need no Walker when you get the latest Colt – a direct descendent of the Walker.”
He handed me a beige looking masterpiece.
“That’s the Close Quarter Battle M45A1 – she’s a beauty,” he said as he nodded towards the weapon, “Seven rounds! And a 5-inch barrel. That will keep you safe.”
I was disappointed. I wanted the Walker. He noticed and offered up an explanation.
“My amigo - you don’t need no parent gun – the great grand daddy. You can just as easily substitute a child gun – a derivative descendant – and she’ll be just as good. What you really need is a weapon, any weapon. And a child direct descendant of the Walker would be perfect.”
I contemplated his reasoning. He then added:
“You know, this is the perfect example of the Liskov Substitution principle in action.”
He continued:
“The object of the derived class (in this case the latest weapon) can easily be substituted for the object of the parent class (the old fashioned Walker) without causing you any problems”.
His logic was impeccable.