Monday, August 27, 2007

Using Nullable to create a null boolean

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/using_nullable_to_create_a_null_boolean.htm]

A classic problem in data mapping is how to handle null values. For example, a database column may be of type int, but it allows null. Many devs will just designate a sentinel value (like Int32.MinValue) to correspond to the DB null. That's okay for integers or DateTimes that have millions of values to spare, but it doesn't work well with booleans where you have only two values. You can't always assume that "null" corresponds to "true" or "false".  There are many common solutions to this:

  • Having an additional property "IsBooleanFieldSpecified" [Problem - this requires an extra property]

  • Not using booleans, and instead using a wrapper that has a third option for Null (like System.Data.SqlTypes.SqlBoolean) [Problem: most devs think in terms of System.Boolean]

  • Requiring all booleans to be not null in the database such that the null problem never appears [Problem: This may not be realistic, especially for legacy systems]

One easy way to handle this with C# 2.0 is with Nullable types. For example, you could write a method that takes a null boolean:


    public static string HandleBool(Nullable<bool> b)
    {
      if (b == null)
        return "NULL";
      else if (b == true)
        return "TRUE";
      else
        return "FALSE";
    }

 

    [TestMethod]
    public void NullableTest_1()
    {
      Assert.AreEqual("NULL", HandleBool(null));
      Assert.AreEqual("TRUE", HandleBool(true));
      Assert.AreEqual("FALSE", HandleBool(false));
    }

 

Note that without the "Nullable" prefix, passing in null would throw a compile error. The solution seems the best of all worlds.

 


Living in Chicago and interested in working for a great company? Check out the careers at Paylocity.

 

No comments:

Post a Comment