throws(statement, ErrorType)
Jonathan M Davis
jmdavisProg at gmx.com
Sun Jan 23 01:09:00 PST 2011
On Sunday 23 January 2011 00:47:13 bearophile wrote:
> spir:
> > How to write a predicate like:
> > assert( throws(someStatement, ErrorType) );
>
> Are you using Design By Contract a lot? Contracts need to contain asserts
> only...
Not necessarily. In fact, in general, the tact that has been taken with Phobos
is that you use assertions when you're verifying that Phobos is correct, and you
use enforce (or an if-statement which throws an exception) when verifying that
arguments given by outside code is correct.
Design By Contract itself says _nothing_ about verifying that a contract is
being followed by not. You could use DbC and _never_ check it, making it
undefined behavior when a contract is violated. After all, DbC says that the
caller _will_ give the function arguments which follow the contract, so if you
don't _have_ to check anything. Obviously, if you want more robust code, you
actually verify that arguments are per the contract, but you don't _have_ to.
In general, I think that an API should throw an exception if bad arguments are
given, not use an assertion. The assertion is _useless_ when dealing with a
public API once it's in a library (except if the function is templated), since
the assertion will already have been compiled out (assuming that you're dealing
with a release build, but that's the most likely case). Using assertions to
verify that your own code is internally consistent is great, but it's not so
great when you have to deal with 3rd parties.
Regardless, from this post and previous posts that you have made, I get the
impression that you're mixing up the concept of Design by Contract and a typical
implementation of it. All that DbC says is that the arguments that a caller
gives a function must meet certain requirements and that if they do, the result
of the function will meet certain requirements. Verifying that the contract is
kept has nothing to do with DbC. It's just good practice if you want to minimize
bugs.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list