1. 10
    1. 1

      With regards to this definition:

      “Defensive Programming amounts to providing (in certain specific build modes) extra code to help ensure that the trusted programmatic clients (within the same process) do not invoke a function and inadvertently fail to satisfy one or more of its preconditions…”

      Is that all encompassing?

      For example let’s say I create shared library that executes a custom set of rules, and produces a result in a form of a string. The custom rules, could be expressed in an embeddable programming language or in a loadable plugin that’s implemented independently from my library..

      One of the constraints that I have, is that my function may not take than 200 milliseconds.

      So

      string tagBusinessTransaction(const CBusinessTransaction& ref)
      

      needs to take no more than 200 milliseconds, if it takes more, return “tooktoomuchtime”.

      I would call a technique to implement such a function, to be, also, ‘defensive programming’.

      That is, I would think that ‘defensive programming’ does not just apply to invocation conditions, but also to certain (although very limited), execution constraints that are not in control of the caller.

      1. 1

        There are a few more things to consider about wide contracts: user expectation & risk.

        My favorite example comes from languages which allow negative indices to be used to index backward from the end of a string or a collection. It seems unnatural or counter-intuitive until you get used to it, but with acclimation it’s just considered normal. It helps that the risk profile isn’t very bad either. The chances of indices into collections rolling over into negative on overflow have decreased as larger integers have become common.

        In general, I favor widening contracts when we can and I push rather hard to see if it is possible. The ideal, for me, is to validate at the highest level and then use more generic code below that can handle cases wider than should ever be needed.