November 22, 2010

DBC Precondition/Postcondition Subclass Rules

Originally published 12 Apr 2007

I was recently in a discussion regarding the precondition and postcondition covariance and contravariance rules of design by contract (DBC) in an inheritance/implementation hierarchy. In order to obey the Liskov substitution principle (LSP) , a subclass or interface implementation can only meet or:
  • Weaken the preconditions of the base class, not strengthen them (contravariance).
  • Strengthen the postconditions of the base class, not weaken them (covariance).
There was some confusion as to why this was the case. So I came up with an analogy to explain. If you think in terms of the client requesting services of an object specifying the preconditions and postconditions, it all makes sense.

So the analogy? Have you ever had to request a help desk ticket? Maybe you need administrative rights or something. And you hope that a specific someone is assigned to that ticket because she's really good and can get the job done quickly and accurately. Let's use that as an example.

The general IT support group contract is:
  • Precondition: Submit a help desk ticket filling in all the forms on the web site.
  • Postcondition: We'll get back to you within two hours.
Now, suppose Suzy Support works in the IT support group. She's really good and efficient. You can think of her as a subclass of the IT support group base class. In the past, whenever I've had a problem and I just happened, purely by chance, to pass her in the hallway and mention it to her, she could solve it in minutes. From my perspective, as a client of the IT support group, that's acceptable.

Suzy's contract is:
  • Precondition: Just tell me the problem. You don't have to fill out a help desk ticket for me. This is weaker than the IT support group's precondition because I have less work to do.
  • Postcondition: I'll solve it in minutes. This is a stronger postcondition. I get better response time.
Make sense?

By the way, for all the IT support group managers out there, this is just an analogy. I know bypassing the help desk ticketing system messes up metrics.

No comments:

Post a Comment