Proper Use of Assert and Enforce

Marc Schütz via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Feb 5 01:57:16 PST 2016


On Friday, 5 February 2016 at 08:45:00 UTC, Minas Mina wrote:
> Use assertions when a variable's value should not depend on 
> external factors.
> For example, let's say you want to write a square root function.
> The input must be >= 0, and because this depends on external 
> factors (e.g. user input), you must check it with `enforce()`.

Or alternatively, you could place the responsibility of ensuring 
that precondition on the caller, in which case you'd use assert().

> The output of the function must should always be >= 0 as well, 
> but this does not depend on any external factor, so use assert 
> for it (a negative square root is a program bug).
>
> auto sqrt(float val)
> {
>     enfore(val >= 0f);
>
>     float result = ...
>     assert(result >= 0f);
>     return result;
> }

For assert()s about values coming from the caller or returned to 
it, you can use contracts, to make it clear that you're not only 
checking an internal invariant of your function:

auto sqrt(float val)
in {
     assert(val >= 0);
}
out(result) {
     if(val == 0)
         assert(result == 0);
     assert(result >= 0);
}
body {
     // use assert()s in the body only for implementation
     // details of your algorithm
     ...
}


More information about the Digitalmars-d-learn mailing list