Derik Whittaker

Syndication

News


Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
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,


Posted 01-22-2008 7:05 AM by Derik Whittaker

[Advertisement]

Comments

Peter Ritchie wrote re: Defensive Coding best practice
on 01-22-2008 10:29 AM

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?

Derik Whittaker wrote re: Defensive Coding best practice
on 01-22-2008 10:38 AM

@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.

Brian wrote re: Defensive Coding best practice
on 01-22-2008 12:33 PM

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.

Derik Whittaker wrote re: Defensive Coding best practice
on 01-22-2008 12:40 PM

@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.

Christopher Bennage wrote re: Defensive Coding best practice
on 01-22-2008 1:07 PM

@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.

Sergio Pereira wrote re: Defensive Coding best practice
on 01-22-2008 1:31 PM

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.

redsolo wrote re: Defensive Coding best practice
on 01-22-2008 3:44 PM

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.

» Daily Bits - January 23, 2008 Alvin Ashcraft’s Daily Geek Bits: Daily links, development, gadgets and raising rugrats. wrote &raquo; Daily Bits - January 23, 2008 Alvin Ashcraft&#8217;s Daily Geek Bits: Daily links, development, gadgets and raising rugrats.
on 01-23-2008 8:10 AM

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

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)