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.
