free hit counter

Thursday, June 23, 2005

almost a justified ASSERT

I almost found a justified use for ASSERT today. If you've read previous posts, or talked with me about programming for any length it's likely you've heard my contention that ASSERT is almost always misused as a substitute for real error handling. I don't think you should ASSERT(sytem("foobar baz")), nor should you ASSERT(fopen(infile)).

I was writing a class to represent hardware registers and their fields. Theoretically these classes are more likely than your average code to be ported to different platforms- 16bit microcontrollers all the way up to a 64 bit Windows machine.

At this point I had an "aha", ASSERT could be quite usefull in ensuring that code will be well behaved when porting to different architectures, a programmer error. E.g. the size of an integer is such a fundamental quantity, a mortal user could never cause anASSERT dealing with integer size to trigger, but a programmer could when porting to a different architecture.

But in my case, the error condition for the programmer error of porting to a machine with a smaller integer size, which an ASSERT would be a handy way to catch, overlaps with the user error of creating too large of a register, and can be caught when creating the class. So, the check for bad input from the user obviates the need for an ASSERT.

boolean tRegister::bitValue(uint bitNumber)
if (bitNumber > bitWidth()-1)
throw runtime_error("bit number exceeds available register size");

uint mask= 1 << bitNumber;
return mValue & mask; }


Post a Comment

<< Home