Michael Perry states in his Pluralsight course on Provable Code (transcript subscription only) that:
[T]he burden of proof rests with the caller
In a code contract, why must the burden of proof rest with the caller and not the method of the class that is being called? Is this a preferred convention or does it have a more solid basis? At the moment it just like a dogma to me as the class being called could make its own safety checks, which would reduce calling code duplication.
3
I’d say that “burden of proof” is the wrong way to think about it. A class with a calling contract can and should validate that the contract is kept by callers. But when it’s not, all it can do is produce an error/exception.
The point of the contract is to state clearly what the calling code must do to produce a correctly working program, so that there are no errors/exceptions. When a code contract is not kept, that’s a programming error. Making the contract explicit helps you to avoid the error.
If you’re serious about code contracts, you want a language where they are enforced by the compiler as much as possible.
1
That’s because it’s the caller the one that passes the parameters.
The caller can pass wrong parameters, hence it must check the exceptions thrown by the callee (or err codes).
As far as I recall, “Don’t blame me, I was only following orders” was rejected as a defence at Nuremburg.
So I would reject out of hand the defence that “Don’t blame my code, it was the garbage it was given”. That does not make for safe, secure or reliable software.
As such, while it is the responsibility of the Caller to provide correct data to the Method, it should also be incumbent on the Method to validate its inputs and handle safely any error conditions.
Just remember, most exploits are there because software doesn’t validate its inputs….
Think of it this way. Suppose you have a web app where one field is the SSN of the user. You grab whatever the user types, remove any non-integer values, and call getName(int), which returns their name. Does it make more sense to have getName() throw an illegal arg exception when the user enters an illegal value, or should your web app first validate the entered value?
You always validate as close to the data as possible.