Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hierarchy violates Liskov - so what?

I am using an API that violates the Liskov substitution principle : it throws its own Exception type that extends Exception, but puts the exception message from the base class in a new ErrorCode field and puts its own (useless) message in the Message field. Therefore to display the correct message I need to cast the Exception to the DerivedException type and use the ErrorCode field. If I treat it as an Exception object I get the wrong message.

Now this irks me on a stylistic level, but it is easy enough to get around : I can just catch DerivedException and use it as the programer intended. So my question is this : what's the big deal about the Liskov principle? What are the practical problems that people might encounter using hierarchies that violate the principle?

like image 541
Aidan Avatar asked Aug 04 '11 08:08

Aidan


People also ask

What violates Liskov Substitution Principle?

A very common violation of this principle is the partial implementation of interfaces or base class functionality, leaving unimplemented methods or properties to throw an exception (e.g. NotImplementedException).

Which of the following are violation of LSP?

LSP violations symptomsDerivates that override a method of the base class method to give it completely new behaviour. Derivates that override a method of the superclass by an empty method. Derivates that document that certain methods inherited from the superclass should not be called by clients.

What is an example of the Liskov Substitution Principle?

Ostrich is a bird, but it can't fly, Ostrich class is a subtype of class Bird, but it shouldn't be able to use the fly method, that means we are breaking the LSP principle.

Why is the Liskov Substitution Principle important?

The Liskov Substitution Principle helps us model good inheritance hierarchies. It helps us prevent model hierarchies that don't conform to the Open/Closed principle. Any inheritance model that adheres to the Liskov Substitution Principle will implicitly follow the Open/Closed principle.


2 Answers

A practical example:

If you would have a logging class with a method LogException(Exception ex) it will log the message you regard useless, instead of the "real" message.

The description of the log method would change from "logs Exception messages" to "logs Exception messages, but sometimes logs useless messages".

like image 65
C.Evenhuis Avatar answered Sep 21 '22 13:09

C.Evenhuis


Function F wants an object of type T, you pass it something that claims to be a valid T, but then behaves differently; ie, there are properties that hold for T, on which F may rely, but your object doesn't satisfy them. What can happen? Pretty much anything. Errors, failures, crashes, your house burning down.

like image 37
LaC Avatar answered Sep 18 '22 13:09

LaC