Disclaimer

The content of this blog is my personal opinion only. Although I am an employee - currently of Nvidia, in the past of other companies such as Iagination Technologies, MIPS, Intellectual Ventures, Intel, AMD, Motorola, and Gould - I reveal this only so that the reader may account for any possible bias I may have towards my employer's products. The statements I make here in no way represent my employer's position, nor am I authorized to speak on behalf of my employer. In fact, this posting may not even represent my personal opinion, since occasionally I play devil's advocate.

See http://docs.google.com/View?id=dcxddbtr_23cg5thdfj for photo credits.

Friday, May 25, 2012

assert/ignore pattern

Here's a pattern I observed today. I have seen it before. (In my wont to record neat little tidbits that m,ay be worthy of further thought.) Started with code:
    Object* objptr = ...;
    assert( objptr->consistency_check() );
    assert( objptr->fooptr->consistency_check() );
    assert( more_consistency_checks(objptr) );
    ... do something with objptr ...
Now, often enough it might be correct not to error exit with an assert. Often enough, in my problem domain, if one of the consistency checks fails you can just ignore the object, and go on. In my domain, computer architecture, this may arise because of speculative execution. So, pseudo-equivalent code might look like
    Object* objptr = ...;
    
    if( ! objptr->consistency_check() ) {
    }
    else if( ! objptr->fooptr->consistency_check() ) {
    }
    else if( ! more_consistency_checks(objptr) ) {
        ... do something with objptr ...
    }
I know, you might prefer
    Object* objptr = ...;
    
    if( objptr->consistency_check()
        && objptr->fooptr->consistency_check() 
        && more_consistency_checks(objptr) ) ) 
    {
        ... do something with objptr ...
    }
but I have found that I often want to do stuff like keep stats for which forms of inconsistencies were found, i.e. which assert would have failed if we had been failing. Or
    Object* objptr = ...;
    try {
      assert( objptr->consistency_check() );
      assert( objptr->fooptr->consistency_check() );
      assert( more_consistency_checks(objptr) );
      ... do something with objptr ...
    } catch(...) {
      ...
    }
although it can be unfortunate if the catch is a long way away from the assert. You might want to specify the assert fail action at the assert - which is what the OF statements do. --- No biggy, just a pattern I have seen before.

No comments: