KevinUp

real world programming

Utils.HasRows

Posted by kevinup on May 8, 2007

 

I hate getting NullReferenceException. It’s the bane of my existence. My feeling is if you get to the point that you get a NullReferenceException, then you haven’t done your job as a developer. I’m also lazy. Who wants to check for Null all the time? Not me. That was one of many reasons I wrote this function:

public static bool HasRows(ICollection list)
{
    if ((list == null) || (list.Count == 0))
        return false;
    return true;
}

There are developers out there that would just do something like this:


List<SearchResults> results = GetSearchResults();
if (results.Count > 0)
{
    //do something
}

The problem is if another developer comes in and changes GetSearchResults() to return null instead of an empty list then things start to bomb. The thing is, at least in this example, you can tell that the logic would be the same, so now to code defensively we do this.


List<SearchResults> results = GetSearchResults();
if (results!=null && results.Count > 0)
{
    //do something
}

Now we make every list that comes back from every call, before we use it we do that. Now our code base is a lot bigger than it needs to be. Enter Utils.HasRows.


List<SearchResults> results = GetSearchResults();
if (Utils.HasRows(results))
{
    //do something
}

I could just ramble on and on about why this is cool, and better and faster, but if you can’t make the connection at this point then you probably would keep writing your ‘== null .count>0’ code.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: