assume, assert, enforce, @safe

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Thu Jul 31 23:04:04 PDT 2014


On Thursday, 31 July 2014 at 21:29:59 UTC, Sean Kelly wrote:
> On Thursday, 31 July 2014 at 21:11:17 UTC, Walter Bright wrote:
>> On 7/31/2014 1:52 PM, Sean Kelly wrote:
>>> Could you expand on what you consider input?
>>
>> All state processed by the program that comes from outside the 
>> program. That would include:
>>
>> 1. user input
>> 2. the file system
>> 3. uninitialized memory
>> 4. interprocess shared memory
>> 5. anything received from system APIs, device drivers, and 
>> DLLs that are not part of the program
>> 6. resource availability and exhaustion
>
> So effectively, any factor occurring at runtime.  If I create a
> library, it is acceptable to validate function parameters using
> assert() because the user of that library knows what the library
> expects and should write their code accordingly.  That's fair.

Yes. It basically comes down to whether you would consider 
incorrect input to the function to be an outright program error 
that should _never_ occur (in which case, you use assertions) or 
whether you consider it reasonable for bad input to be given some 
of the time or unreasonable to require that the caller never give 
bad input (in which case, you use exceptions).

Also, if efficiency is of great concern and it's possible for the 
caller to guarantee that the input is valid (which wouldn't be 
the case with something like files, because even if the input was 
validated, it could become invalid afterwords), then using 
assertions might be a better approach. On the other hand, if 
correctness is of greater concern, then it might make more sense 
to use exceptions, because then it makes sure that the programmer 
is never able to give bad input (though if it really makes more 
sense to treat that as program bug - e.g. giving an invalid index 
- then using Errors or assert(0) might make more sense, since 
they'd stay in but be immediately fatal).

All in all, while some cases are very clear-cut as to whether 
assertions or exceptions should be used, many of other cases are 
highly subjective, at which point it generally comes down to 
whether bad input to the function should be considered a 
programming error or whether it makes more sense for the function 
to throw and allow the program to try and recover from the 
problem.

- Jonathan M Davis


More information about the Digitalmars-d mailing list