Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



Defensive Coding best practice

<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,



Comments

Peter Ritchie said:

For the most part, this is how people deal with null references; and in the case of searching, this is very logical--null means "not found".  But, in the case where a null reference really is an exceptional thing, what do you normally do?  Would you:

a) let it get thrown--not checking for null?

b) catch it and throw another application-specific (presumably value-added) exception

c) check for null and return an "error" condition/code

d) none of the above?

For example the Items and the SelectedItem properties?

# January 22, 2008 10:29 AM

Derik Whittaker said:

@Peter,

It all depends on the case, but if a null is found and it is NOT expected, then i like option B.

In our case we just accept that nothing was found and continue on.  So i could have wrapped it in a try catch and then just swallow the exception that that is just evil.

# January 22, 2008 10:38 AM

Brian said:

I would go farther and say what if:

listMain is null

listMain.Items is null

listChild is null

listChild.SelectedItem is null

listChild.SelectedItem.Text is null or empty string.

If it is an object, technically it can be null.

# January 22, 2008 12:33 PM

Derik Whittaker said:

@Brian,

Technically i would agree with you, but you have to pick your battles.  Checking the UI control for null may be a little overboard.  But i agree with the .Items and .SelectedItem.

# January 22, 2008 12:40 PM

Christopher Bennage said:

@Peter, I'd go with B too.  But I can also imagine "it depends" cases.  Not that any one has suggested it, but I would not use exceptions for flow control.

# January 22, 2008 1:07 PM

Sergio Pereira said:

This is an example of why I think the ListBox/DropDownList family of controls are some of the worst things in ASP.NET. Trying to find an item and selecting it is such a common case that the API should have the "easy button" when you don't care to throw exceptions. Hooray for extension methods.

# January 22, 2008 1:31 PM

redsolo said:

Lately Ive stopped doing defensive programming since, I want the null reference to be thrown because the null reference is an error. If its hidden with defensive programming you never know when it shows up later. I rather have it fail early than later when its harder to find the origin of the null reference.

# January 22, 2008 3:44 PM

» Daily Bits - January 23, 2008 Alvin Ashcraft’s Daily Geek Bits: Daily links, development, gadgets and raising rugrats. said:

Pingback from  &raquo; Daily Bits - January 23, 2008 Alvin Ashcraft&#8217;s Daily Geek Bits: Daily links, development, gadgets and raising rugrats.

# January 23, 2008 8:10 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Proudly Partnered With


This Blog

Syndication

News