Skip to main content

SOLID: Liskov Substitution Principle

About 5 years ago, I wrote a series of short articles on the SOLID principles, shared by email to my colleagues as a weekly, Monday morning read. They were then archived for reference to our internal knowledge base. That's getting a revamp and re-platforming now, and given their age, I'm not sure these pieces will be making the cut. Given it's fairly timeless stuff, seems a shame for them to disappear into the virtual ether, so I'll save them for posterity here.

The SOLID Principles

The SOLID principles are a well established set of tenets intended to guide software design toward a maintainable solution. They are widely applicable and operate at a high level, so are well worth considering for almost any type of application we are looking to build, using any framework or language.

For the full set of articles in the series, see:

L is for Liskov Substitution Principle

The Liskov Substitution Principle (LSP) is named after a lady called Barbara who formally expressed it as: Let q(x) be a property provable about objects x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T. Which is a bit of a mouthful and so most people know it as Subtypes must be substitutable for their base types.

This means that any time you have a piece of code that relies on a particular base type, passing in a derived type instead should work correctly. There shouldn't be any need to do specific checks to see if a particular derived type is being used and act on that information by changing the logic of the method.

You can find lots of abstract examples of this online, usually using squares and rectangles but for something more real-world and related to my company work I struggled to come up with one at the time. So to illustrate instead referenced instead this example, which seemed like something we certainly could come across.