Monday February, 20 2006

Throw exceptions, don't return null    \\ coding

One of the simple coding practices that has become a pet peeve of mine over the years is the reluctance of most developers to throw exceptions. I find that many developers still like to return a null value rather than throw an exception and thats something that needs to change. There are certainly going to be situations where returning null might make some sense, but most of the time you should be throwing exceptions.

I found a fairly short article titled Diagnosing Java Code: The Null Flag bug pattern which does a pretty good job of illustrating the potential pitfalls with the null flag pattern.

One place where I see the null flag pattern used in one of the worst scenerios is with DAOs. Many applications which access persisted data will setup a data access layer which provides classes and methods for creating, updating, deleting, and retrieving data. Very often the designers of this data access layer will allow their data retrieval methods to return null values rather than throw an exception. The big problem in this case is that presumably the caller of the method isn't just hoping for a value, they are expecting a value and when a value cannot be returned that is an error case. Rather than hope that the caller properly checks for a null return value an exception should be thrown.

I know how hard it can be to break old programming habits, but this is one of those very fundamental patterns which really deserves the extra effort. Trust me, you'll be doing everyone a favor by just throwing some more exceptions.

Posted by gconf at Feb 20 2006, 10:39:05 AM PST | Permalink | Comments (0)
Comments:

Post a Comment:
Comments are closed for this entry.

Search

The Grabbag

Powered by
Roller Version 4.0.1.1 (BSC)
© copyright gconf ... don't copy me!