While investigating a routine bug fix today, I came across some code that can only be described as a buried cry for help …

public void Adjust(
    DateTime? open, DateTime? due, DateTime? close)
    if (!open.HasValue)
        throw new ArgumentNullException("open");
    if (!due.HasValue)
        throw new ArgumentNullException("due");
    if (!close.HasValue)
        throw new ArgumentNullException("close");
    // ...

Why would a developer declare parameters as nullable DateTimes and then immediately write guard clauses to prevent nulls from being accepted.

If you don’t want to support nulls, use a regular date time.

There are two lessons to learn here, one specific and one general.

The specific lesson: Use the right type for each parameter - use the most liberal type that makes sense (for example, use IEnumerable<T> instead of IList<T> unless you need indexed access), but no more liberal (don’t use DateTime? unless you’re willing to accept nulls).

The general lesson: Don’t make code more complex than it needs to be - do things the simplest way that makes sense. Being a developer is hard enough, we shouldn’t go out of our way to make it harder.


blog comments powered by Disqus
Next Post
Looking forward to 2012  31 Dec 2011
Prior Post
A story about Magic  10 Dec 2011
Related Posts
When (not) to use Var  16 Jul 2016
Semantic Types Redux  05 Jun 2016
Semantic Types in C#6  27 May 2016
Property Enhancements for C#  20 Dec 2015
Language Extensions for C#  19 May 2014
When should methods be Static?  09 Oct 2012
Of Method Naming and more  29 Sep 2012
CallerInfo in C# 5  08 Dec 2011
Regions in C#  16 May 2011
Lambda expressions and Block syntax  15 Apr 2011
More csharp posts »
Related Pages
December 2011 archive