The problem with null

The problem with null is that it pretends to be an object of a given type, without actually having that type. For example (C# code - ignore the uselessness of the GetName method):

  string GetName(Customer customer)
  {
    // I got a customer object, I can access the Name property
    return customer.Name;
  }

  var x = func(null); // <-- not a real Customer object so we have a run-time error

The proper way to solve this is by using the Option (aka Maybe) monad; for an example using the Functional.Maybe NuGet package:

  string GetName(Maybe<Customer> customer)
  {
    // I don't actually have a Customer object, I have a Maybe<Customer>
    // I need to treat it carefully
    return customer.Select(it => it.Name).OrElse("Missing");
  }

  var x = func(null); // compiler error, because Maybe<> doesn't allow null as a value
  var x = func(Maybe<Customer>.Nothing); // the customer is missing but the call will not crash

Using the Option monad is basically a way of forcing a compile-time check for nulls, instead of waiting until run-time.

Comments

Popular posts from this blog

Posting dynamic Master / Detail forms with Knockout

Comparing Excel files, take two

EF Code First: seeding with foreign keys