December
27

Guys, will you knock it off with returning nulls from methods? You should return Special Cases, not nulls! nulls tend to bypass any polymorphic structure, and cause code to be cluttered with null checks. For example:

public IEnumerable<Picture> GetAllPictures()
{
  if ( .. there are pictures .. )
  {
    return pictures;
  }
  else
  {
    return null;
  }
}

Oh boy, users of this method would have to check for nulls every time before they operate on it: (if they don’t they might get a NullReferenceException, which s-uhhh-cks)

var pictures = GetAllPictures();
if (pictures != null)
{
  foreach (var picture in pictures)
  {
    …
  }
}

Isn’t that null check a big distraction from the actual logic? If you use a Special Case for that enumerable and return Enumerable<Picture>.Empty(), the calling code could be reduced to:

var pictures = GetAllPictures();
foreach (var picture in pictures)
{
  …
}

Much better, no?

kick it on DotNetKicks.com

2 Comments

[…] my post on the Special Case pattern, I just wanted to give a few more examples in which the pattern proves to be really helpful. In […]

One of the issues with returning IEnumerable is that it may not be efficient to get a count.

For this reason, I find it handy to use an IEnumerableEx class that supports a Count for the cases where we want to stream values but know the total beforehand.

Something to say?

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.