Junior Mistakes#

I'm currently having fun at a client migrating the custom .NET framework I've helped build 3,5 years ago to the wonderful world of .NET 2.0. One of the more confronting things about it is that I stumble across pieces of code that I'm not really proud of or would do totally different today.

I'll spare you the details, but I think the following code snippet that I just came across says enough:

Public Class DataSetHelper

    Private m_Data As DataSet

    Public Sub New(ByVal data As DataSet)

        If data Is Nothing Then
            Throw New NullReferenceException("Class cannot be instantiated with its DataSet set to null.")
        End If
        m_Data = data

    End Sub

    ' Snip...

End Class

That just feels like throwing an OutOfMemoryException yourself... In my defense: at least I was doing argument checking ;-)

Time sure has flown since I was thrown into .NET 1.0... What's your favorite junior mistake?

Update: as a co-worker correctly pointed out, I should probably elaborate a bit on why this is a mistake...

Throwing a NullReferenceException is something that you should never do yourself. Just like throwing that OutOfMemoryException. It's a task that is reserved for the CLR when it finds that some code is invoking a method on a reference that has no object instance (a.k.a. it's null). To quote the MSDN documentation on NullReferenceException: "The exception that is thrown when there is an attempt to dereference a null object reference. Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here."

So if you want to validate that arguments which have been passed into a method, are null but shouldn't be, then you should simply throw an ArgumentNullException with just the parameter name and nothing more:

If data Is Nothing Then
    Throw New ArgumentNullException("data")
End If

For more fun with NullReferenceExceptions, don't miss my winning contest entry on Brad Abrams' pop quiz.

Comments are closed.
All content © 2012, Jelle Druyts
On this page

Recent Photos
www.flickr.com
This is a Flickr badge showing public photos from Jelle Druyts. Make your own badge here.
Advertising
Top Picks
Statistics
Total Posts: 350
This Year: 0
This Month: 0
This Week: 0
Comments: 530
Archives
Sitemap
Disclaimer
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.0.7226.0

Sign In