SOLID Principles : Part 3 of 5, Liskov Substitution Principle

The Liskov Substitution Principle was written about in 1998 by Barbara Liskov. LSP states that subtypes must be substitutable for their base types. OK this is kind of confusing, what is a subtype and what is a base type?

Lets use an example of a car door as our base type. The subtype will be the doors to a fancy sports car.

Often when we have a subtype we might use the IS_A, analogy to figure out if it is a subtype. IS_A Lamborghini door a type of door? YOU BETCHA IT IS. The five dollar word for this is called polymorphism.

Below we have some example code of what our door class might look like. This code doesn’t compile just using a general structure, so don’t try to run this code at home.

Cool you have a door, pulling it opens the door, pushing the door closes it.

Uh, uh, uh, someone forgot about about the 0.000001% when implementing their polymorphism didn’t they!

Don’t forget about the ultrawealthy.

Who is that? It’s Russ Hanneman, the person that put radio on the internet, and his car doors go vertically, up and down.

The Liskov Substituiotn Princple is broken because, this sports car door which inherits for our regular car door causes both the push and pull functions to misbehave. Remember subtypes must be substituable for their base types.

Even worse when breaking LSP we often are breaking the Open Closed Principle as well. Our base door class has no room for extension. Even something as simple as a square inheriting from a rectangle can break LSP.

One way of making sure we are following LSP is using something called Design by Contract. You can read more about that here, but the gist of it is we throughly test the behavior of the a base class so the intent of what that class does is clear. Anything that dervies from that base class must accept and must conform to all of the precondtions and postconditions of the base class.

Preconditions could be which direction a door opens, which is horizontally only. That way if someone tries to inherit for the base class with these types of door that they shouldn’t be doing that. Postcondition could be the expected result, pulling from the outside part of the car opens it. Pushing from the outside closes it. So automatic minivan doors could not inherit because the pulling on the door handle both closes and opens the door.

Tune in next time when we talk about the Interface Segregation Principle!