Contracts, Undefined Behavior, and Defensive,Programming

Mark smarksc at gmail.com
Sun Jun 14 12:49:53 UTC 2020


On Saturday, 13 June 2020 at 03:46:38 UTC, Andrei Alexandrescu 
wrote:
> A short and sweet paper:
>
> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1743r0.pdf
>
> It echoes Walter's opinions on contracts vs. runtime checking, 
> to a tee. He has been derided on occasion in this group for 
> such views. The paper is a good rationale from an independent 
> source.

Interesting paper.

They mention that some preconditions can't be checked, or aren't 
feasible/worthwhile to check. While this is true, I think in most 
circumstances it is possible (and quite useful) to limit the 
effects of out-of-contract function invocations (or "soft UB" as 
they call it) by providing "guaranteed postconditions", for lack 
of a better expression. To borrow their example, consider:

void sort(std::vector<int> &vec, Comparator comp);
// Precondition: $comp provides a strict weak ordering on 
integers.
// Postcondition: $vec is sorted with respect to the order 
dictacted by $comp.
// Guaranteed postconditions (even if preconditions are 
unfulfilled): No data is modified except that which is accessible 
through $vec, no exceptions are thrown, no memory corruption 
occurs and no language-level UB occurs.

In other words, invoking sort with an invalid comparator might 
mess up the given vector, but at least no "catastrophes" occur. 
Luckily, in D we have attributes (pure, @safe, nothrow) that 
basically impose such useful "guaranteed postconditions" and are 
mechanically checkable.


More information about the Digitalmars-d mailing list