Woozle Wuzzle
Coding Defensively

Tip: Never check for a single value when you actually are interested in a range.

The common case where this occurs is with sizes (list, arrays, etc). The statement:

if(list.size() == 3)
    return;

or:

for(int i=0; i!=10; i++)
    ...

is error prone and should be avoided at all costs. Why? Most of the time the list will have multiple entries added (this is especially poignant in the case of MT (multi-threaded) code) and an equality can be missed. In the for-loop case, it is common (but oooohhh so bad) to see the loop counter manipulated in the loop body. So the correct statements would be:

if(list.size() >= 3)  // or (list.size() > 2)
    return;

and

for(int i=0; i<10; i++)
    ...

This is called coding defensively. You're preventing bugs before they've had a chance to form.

Comments
Post a comment













Remember personal info?






Creative Commons License Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License.