How do you test pre-/post-conditions and invariants?

Magnus Lie Hetland magnus at hetland.org
Sat Feb 26 07:08:06 PST 2011


On 2011-02-26 15:20:19 +0100, David Nadlinger said:

> On 2/26/11 1:15 PM, Jonathan M Davis wrote:
>> [...]  And from a perfectly practical standpoint, as soon as your code ends
>> up in a library, assertions are generally useless anyway,[...]
> 
> I don't quite think asserts are useless in libraries. If you need to 
> care about performance in a library, you hit cases quite frequently 
> where sanity-checking the input would be too expensive to be done in 
> release mode, and thus you can't specify behavior on invalid input as 
> part of your API using exceptions. Nevertheless, it is still useful to 
> people using your library to get notified when they are messing 
> something up as early as possible in debug mode, which is precisely 
> what asserts are made for, at least in my opinion.

But that would only work if they had access to the source, or a version 
not compiled in release mode, right?

Hmm.

This is also related to what Jonathan said about programming by 
contract -- and only using in-clauses (for example) when you also 
control the calling code. I guess what you're saying could be an 
argument in the other direction: that even though they certainly 
shouldn't be considered part of the public API (beyond documenting what 
would be input causing undefined behavior), they *could* be useful in a 
library that a client could use in debug mode, because it gives them 
some extra tests for their own code, "for free". They can test that 
their own code is using your code correctly.

That sounds quite in line with programming by contract to me ... but 
then, again, I'm a reall n00b on the subject :)

-- 
Magnus Lie Hetland
http://hetland.org



More information about the Digitalmars-d-learn mailing list