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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s