Tuesday, October 25, 2016

Defensive Programming Done Right

I watched John Lakov's two part video on Defensive Programming Done Right [1, 2]. 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 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.
  • A function's postcondition is simply its return value. 
  • A method's postcondition is subject to the preconditions of the method and the object state when the method is called. 
The extension of pre- and post-conditions to methods introduces the notion of essential behaviour. Essential behaviour includes method postconditions but also other behavioural guarantees beyond these postconditions. These behavioural guarantees are essential to ensuring the method's correctness.

Both talks provide an introduction to the C++ proposal for Centralized Defensive-Programming Support for Narrow Contracts. Indeed, the implementation of BDE (of which BSLS is a component). 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 a great deal of 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 the value of 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 that the C Standard Library embodies better solutions.

[1] Defensive Programming Done Right, Part I
[2] Defensive Programming Done Right, Part II

No comments:

Post a Comment