assert vs enforce?

Robert Clipsham robert at octarineparrot.com
Sat Jan 22 16:38:54 PST 2011


On 23/01/11 00:33, Sean Eskapp wrote:
> What's the difference between assert and enforce in D?

Use assert() for something that must almost be true, regardless of user 
input, or anything else.

enforce() on the other hand is for things which may or may not be true. 
The source code should clear things up:
----
T enforce(T)(T value, lazy Throwable ex)
{
     if (!value) throw ex();
     return value;
}
----
So it's essentially just shorthand for throwing an exception.

Example:
----
void main(string[] args)
{
     enforce(args.length > 2, "The user needs to pass the correct 
parameters");
     assert(1+1==2, "If this isn't true, the application should terminate");
}
----

-- 
Robert
http://octarineparrot.com/


More information about the Digitalmars-d-learn mailing list