7

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?

Aidan
  • 4,783
  • 5
  • 34
  • 58
  • 1
    So the thrown exception does not wrap the original exception, something like: `throw new DerivedEx("message", originalEx)`? That is bad and it is the reason that you need to cast it. Ask the developers of the API to fix this. Ask them to read the [Framework Design Guidelines](http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613). – Steven Aug 04 '11 at 08:12
  • Is exactly right. I am going to ask them, just anticipating their objections, which will effectively be "So What?" – Aidan Aug 04 '11 at 08:24

2 Answers2

8

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".

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
1

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.

LaC
  • 12,624
  • 5
  • 39
  • 38