Liskov substitution principle with abstract parent class

abstract classinheritanceliskov-substitutionobject-oriented-designsolid

Does Liskov substitution principle apply to inheritance hierarchies where the parent is an abstract class the same way if the parent is a concrete class?

The Wikipedia page list several conditions that have to be met before a hierarchy is deemed to be correct. However, I have read in a blog post that one way to make things easier to conform to LSP is to use abstract parent instead of a concrete class.

How does the choice of the parent type (abstract vs concrete) impacts the LSP? Is it better to have an abstract base class whenever possible?

Best Answer

You can answer questions like this by going back to first principles and asking "what is the Liskov substitution principle intended to accomplish?" And the answer to that is that code that works correctly with the superclass should also work correctly with all subclasses. (For CS theory purposes there is a more specific mathematical definition but for the workaday programmer that's likely to only be concern if you are creating a programming language).

So, why would an abstract class be easier? There really is no situation where using a concrete class means you can't possibly follow the Liskov substitution principle in your subclasses. After all, the superclass defines a contract for the subclasses either way. The fact that it also contains one possible implementation of the contract is neither here nor there.

However, one might make the argument that psychologically it's easier to focus on a contract when making an abstract class, and perhaps a concrete class might take an implementation detail and accidentally make that part of the contract. It seems sort of plausible without being really convincing.

As far as never using a concrete class - perhaps a good rule of thumb is to be a bit skeptical of any design philosophy that says you should never use a standard, not totally broken feature of a language. In this case, the chance that you might, maybe, be more likely to make a mistake designing the contract of a concrete class vs. an abstract one - well that would be at best a minor factor in making that decision.

Related Topic