Assert and the optional Message
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Mar 9 11:59:15 PST 2012
On Fri, Mar 09, 2012 at 02:38:48PM -0500, Jonathan M Davis wrote:
> On Friday, March 09, 2012 11:29:43 H. S. Teoh wrote:
> > Hmph. Well, then that defeats the purpose of checking contracts,
> > because checking contracts is only justifiable if it's complex
> > enough, which means that it's liable to involve things like dtors
> > and scope statements. It's silly to want to check a trivial contract
> > like assert(x>0);, because if something *that* simple can go wrong,
> > then so can the unittest, so you're not proving anything at all.
> >
> > But this isn't that big a deal. One could argue that if a contract
> > is convoluted enough to warrant a unit test, then perhaps most (or
> > all) of its complexity should be factored out into a separate, unit
> > tested function, which is then just invoked from the contract.
> >
> > (I find this a bit ironic, since TDPL states that the reason
> > contracts allow statements is so that complicated conditions can be
> > tested for, rather than being limited to just a single expression,
> > as is the case in most other languages that support DbC. Now it
> > seems that simple contracts are the way to go.)
>
> It's only an issue if you're trying to test your contracts, and I
> don't think that that's a very typical thing to do. That's kind of
> like writing tests to test your unit tests.
I was thinking of cases like a function that performs complicated
numerical computations, and the out contract is to assert that the
results make sense (e.g., you're not getting total garbage due to
accumulated roundoff errors). Sometimes checking if the results are
consistent is non-trivial.
But then again, if it's *that* non-trivial, it really shouldn't be
directly inside a contract, but in a separate function.
> And the ability to have complicated conditions in contracts is still
> better than having a single expression even if you do want to test
> your more complicated contracts, because it allows you to have
> multiple assertions rather than just one expression, and then you know
> _which_ condition was false and can provide a decent error message
> (e.g. one which included the values of some of the arguments) instead
> of having one big condition that either succeeds or fails and really
> doesn't give you any useful information beyond that (like you get with
> template constraints).
[...]
I wasn't arguing for using only a single expression in contracts at all.
I was just commenting that allowing statements makes it possible to do a
whole lot more, including stuff that perhaps one shouldn't be doing
inside a contract. But I've always believed in flexibility vs.
unnecessary restrictions. Preventing the programmer from doing stupid
things will also prevent her from doing clever things, as the saying
goes.
T
--
MAS = Mana Ada Sistem?
More information about the Digitalmars-d-learn
mailing list