—A look at defensive programming and Narrow Contracts in C++.
I watched John Lakov’s two part video on Defensive Programming Done Right (Part I and Part II). The first part provides motivation for defensive programming. The second, shows how to use BSLS to introduce defensive programming into C++. A definition of defensive programming is provided in Part I.
Part I looks at design by contract and observes that undefined behaviour in a contract can be advantageous. Particularly if you structure your implementation so that sensible behaviour occurs whenever preconditions are violated.
Sensible behaviour is delegated to the application. Doing so simplifies library construction. For example, the Standard C Library’s handling of null pointers provided to string functions is implemented this way.
A model is discussed for pre- and post-conditions applied functions and methods.
Both talks provide an introduction to the C++ proposal for Centralized Defensive-Programming Support for Narrow Contracts. The implementation of BDE (of which BSLS is a component) contains support for this proposal. The experience gained at Bloomberg using BDE provides the practical element of this proposal.
Centralized Defensive-Programming Support for Narrow Contracts defines a narrow contract as a combination of inputs and object state that can result in undefined behaviour detectable only at runtime. There is an excellent argument in this paper for not artificially widening a contract–an argument that the Standard C Library supports and which the Standard Template Library may have missed (for example with the introduction of the Vector container’s at method).
In all, I had difficulty finding value in Lakov’s videos but think that this is a result of his presentation style rather than the content contained therein. Lakov is a co-auther of Centralized Defensive-Programming Support for Narrow Contracts and that work and the ideas contained therein made clear what the videos did not.
I haven’t done any research on what prompted the Vector at methods and the notion of artificially widened contracts but I am convinced the C Standard Library embodies better solutions.