Against enforce()

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 18 05:37:15 PDT 2011


On Fri, 18 Mar 2011 04:14:12 -0400, Kagamin <spam at here.lot> wrote:

> Walter Bright Wrote:
>
>> 1. Asserts and contracts are for detecting program BUGS. They are not  
>> for
>> validating user input, checking for disk full, file not found errors,  
>> etc.
>>
>> 2. Enforce is for validating user input, checking for disk full, file  
>> not found
>> errors, etc. Enforce is NOT for use in contracts or checking for  
>> program bugs.
>>
>>
>> Any use of enforce in Phobos that is checking for program bugs is  
>> itself a bug
>> and should be entered into bugzilla for fixing.
>
> So this is a bug? This is a contract, not a validation of user input.
>
> struct Iota(N, S) if ((isIntegral!N || isPointer!N) && isIntegral!S)
>  {
>     private N current, pastLast;
>     private S step;
>     this(N current, N pastLast, S step)
>     {
>         enforce((current <= pastLast && step > 0) ||
>                 (current >= pastLast && step < 0));
>         this.current = current;
>         this.step = step;

This is a good example of why it's difficult to decide what "user input"  
is.  One could consider that the 'user' in this case is the developer  
using the library, but I don't think that's the right choice.

I'd say it's a bug, this is clearly a contract, since the data being  
passed into the ctor can easily not be user input (i.e. it's most likely  
two literals that will never depend on a user).  If it is user input, the  
caller of the ctor should enforce the user input before passing it to iota.

-Steve


More information about the Digitalmars-d mailing list