<disclaimer>
This posting is purely my personal opinion. I am sure many of you out there will disagree, if this is the case, let me know.
</disclaimer>
Today, during my bug hunting I stumbled across the dreaded 'Null reference' exception. This was not the original target of my hunt, but it quickly became wanted bug number one. After some digging and debugging I found the the varmint. The offending code was the following a null ref because someone made the mistake of assuming that an object would always be non-null.
listMain.Items.FindByText( listChild.SelectedItem.Text.Substring( 0, 1 ) ).Selected = true;
Now let me explain the intent of this code. There are 2 list boxes on the UI and when someone selects something in the second list box, the code is meant to filter down the code in the first list box. However, the code above assumes that there will be a match for the 'FindByText' method and this is where we have problems. The author of this code decided that there will NEVER be a situation where the filter will not find a result. Oops.
The defensive coder would not make that assumption and would have added a few extra lines of code. Below may be an example:
ListItem foundItem = listMain.Items.FindByText( listChild.SelectedItem.Text.Substring( 0, 1 ).ToUpper() );
if ( foundItem != null )
{
foundItem.Selected = true;
// Do something with the result
}
else
{
// Do something, either tell the user there was no data or anything else the business wants
}
By adding the defensive code we can avoid the 'Null Reference' exceptions that we all love. We also make our code more robust by forcing the developer to thing about possible exception conditions.
For more information about Defensive Coding, check out this link here.
Till next time,
Posted
01-22-2008 7:05 AM
by
Derik Whittaker