On Wed, Feb 04, 2015 at 04:24:14PM -0800, Andrei Alexandrescu via Digitalmars-d wrote: > I'm seeing another idiom that seems to become fashionable. Consider this > excerpt from > https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L407: > > auto opSlice(size_t low, size_t high) > in > { > assert(low <= high); > } > body > { > import std.range : take; > return this[low .. $].take(high - low); > } > > which of course trivially boils down to: > > auto opSlice(size_t low, size_t high) > { > assert(low <= high); > import std.range : take; > return this[low .. $].take(high - low); > }
I disagree. Putting the assert in the contract means you're putting the onus on the *caller* to ensure parameters are sane. An assert inside the function body should not be vetting function arguments; that's the wrong use of assert. Asserts inside the function body should be checking for sanity *within* the function body. Requirements on parameter values are something that the *caller* should ensure, and therefore should be in the in-contract, so that the documentation will include it, and readers of the code will know what are the correct arguments to pass (they should not need to read the function body to know this). The fact that currently in-contracts generate the asserts in the callee rather than the caller (which is probably what led you to your conclusions) is a long-standing mis-implementation of DbC that, one could hope, will finally get fixed now that it is receiving some spotlight. In-contracts should be generated in the *caller*, so that any breach of contract will fail on the caller's side. This is a particularly major problem in shared libraries: when you ship a library, you generally compile it with -release, but since in-contracts are emitted in the callee's body, the asserts are skipped in -release mode, so the result is that there is *no* DbC in the shipped library. This alone puts a big dent in the usefulness of DbC in D, reducing it to nothing more than pretty (or, in this case, not-so-pretty!) syntax for what's otherwise nothing more than a glorified assert. T -- "I suspect the best way to deal with procrastination is to put off the procrastination itself until later. I've been meaning to try this, but haven't gotten around to it yet. " -- swr
