Program logic bugs vs input/environmental errors

Bruno Medeiros via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 7 07:00:33 PST 2014


On 29/10/2014 21:22, Walter Bright wrote:
> On 10/29/2014 5:37 AM, Bruno Medeiros wrote:
>> On 18/10/2014 18:40, Walter Bright wrote:
>>> As I've said before, tripping an assert by definition means the program
>>> has entered an unknown state. I don't believe it is possible for any
>>> language to make guarantees beyond that point.
>>
>> The guarantees (if any), would not be made by the language, but by the
>> programmer. The language cannot know if a program is totally broken and
>> undefined when an assert fails, but a programmer can, for each particular
>> assert, make some assumptions about which fault domains (like Sean put
>> it) can
>> be affected and which are not.
>
> Assumptions are not guarantees.
>

Let me give an example:

double sqrt(double num) {
   assert(num >= 0);
   ...

With just this, then purely from a compiler/language viewpoint, if the 
assert is triggered the *language* doesn't know if the whole program is 
corrupted (formatting the hard disk, etc.), or if the fault is localized 
there, and an error/exception can be thrown cleanly (clean in the sense 
that other parts of the program are not corrupted).

So the language doesn't know, but the *programmer* can make a reasoning 
in each particular assert of which domains/components of the program are 
affected by that assertion failure. In the sqrt() case above, the 
programmer can easily state that the math library that sqrt is part of 
is not corrupted, and its state is not totally unknown (as in, it's not 
deadlocked, nor is it formatting the hard disk!). That being the case, 
sqrt() can be made to throw an exception, and then that "assertion" 
failure can be recovered cleanly.

Which leads to what you say next:

> In any case, if the programmer knows than assert error is restricted to
> a particular domain, and is recoverable, and wants to recover from it,
> use enforce(), not assert().
>

Very well then. But then we'll get to the point where enforce() will 
become much more popular than assert to check for contract conditions. 
assert() will be relegated to niche and rare situations where the 
program cant really know how to continue/recover cleanly (memory 
corruption for example).

That idiom is fine with me actually - but then the documentation for 
assert should reflect that.

-- 
Bruno Medeiros
https://twitter.com/brunodomedeiros


More information about the Digitalmars-d mailing list