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:
Post a Comment