Search code examples
c++carchitectureparadigms

Whose resposibility should it be to check preconditions?


In procedural languages where functions are a key player, the design by contract paradigm basically says that there is an agreement between a function that takes parameters and the caller.

The agreement goes something like "if the caller ensures that the preconditions of the function are met, then the function will behave in an expected manner and/or return expected values."

If we write code strictly in this way, then the caller alone is responsible for ensuring proper inputs to functions. But in the name of defensive programming, it seems wise to include internal safeguards in case the caller does something stupid.

When it come to software architecture and design, what is the best approach here?


Solution

  • It's the responsibility of the caller. For example, what could an implementation of strlen do if passed a null pointer? The only thing it could do is abort the program - which is a viable, if drastic, option in C. In C++ it could throw an exception (but not if it adheres to the C++ Standard), but dealing with that exception would be very difficult. So the only sensible solution, that allows the program to keep running in a known state, is for strlen not to be called with a null pointer as a parameter, placing the onus for checking this on the calling code.