Invariant and pre/post-conditions order

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 19 20:19:02 PST 2012


On Thu, 19 Jan 2012 22:31:08 -0500, Walter Bright  
<newshound2 at digitalmars.com> wrote:

> On 1/19/2012 6:37 PM, Steven Schveighoffer wrote:
>> I have to disagree on some level with (1). It might not make a  
>> difference in
>> determining there is a bug, but it makes a difference because failing  
>> in the
>> out-condition gives you more information, even if the invariant is  
>> broken. It
>> tells you which function broke the invariant.
>
>
> No, it doesn't give you more information in the out condition.  
> Furthermore, the postcondition and the invariant check entirely  
> different state - the return value is not the same thing at all as the  
> instance state. There's no reason to believe that one is superior to the  
> other, nor that they are redundant.

If they are related, yes it does give you more information.  The out  
condition might not check the class data directly, but the error which  
caused the invariant to fail could have also caused the out-condition to  
fail.  It's inconsequential to the *program* whether the out condition or  
the invariant halts execution.  But to the developer receiving the assert  
message, it's much more helpful to see an out condition failing than an  
invariant.  If they are related, and caused by the same bug, it's that  
much more helpful.  Imagine you have 1000 lines of code that call 50 or so  
different methods on a class.  Any one of those calls in any one of those  
methods could cause an invariant failure.  But only one method call can  
cause a specific out condition failure, and the lines of code that call  
that function might be significantly less than 1000 (maybe a handful).

With almost no change to execution speed, semantics, or pretty much  
anything, you will have saved the developer minutes to hours (under the  
right circumstances, maybe even days or weeks) of crappy "how the hell do  
I find this bug" time.  I can't see a single drawback aside from the time  
it takes to test the changes to the compiler.

even your second reason is flawed -- in order for there to be a noticeable  
difference, one would have to make their invariant actually *change* the  
object.  Why do we support that?  In fact, this change would help them  
discover their flawed invariant code :)

-Steve


More information about the Digitalmars-d mailing list