Null Reference Avoidance with Maybe - Tigra-Astronomy/TA.Utilities GitHub Wiki

Maybe<T>

One of the most insideous bug producers in .NET code is the null value. Do you return null to mean "no value"? What's the caller supposed to do with that? Did you mean there was an error? Did you mean there wans't an error but you can't give an answer? Did you mean the answer was empty? Or did someone just forget to initialize the variable?

Microsoft knows this is a problem so they have introduced Nullable Reference Types. However, in our opinion, the syntax is clunky and doesn't really make for more readable code. Also, they can't even get the name right. Reference types were always nullable.

Far better to avoid the need for null values altogether. This, and the ambiguity between "error" and "no value" is why we created Maybe<T>.

Maybe<T> is a type that either has a value, or doesn't, but it is never null. The idea is that by using a Maybe<T> you clearly communicate your intentions to the caller. By returning Maybe<T> you nail down the ambiguity. When you have a Maybe<T> you know:

"There was no error, but there might not be a value and you have to check".

Strictly, a Maybe<T> is an IEnumerable<T> which is gauranteed to contain 0 or 1 elements. Maybe<T> implements IEnumerable<T> and that means you can use certain LINQ operators:

  • maybe.Any() will be true if there is a value.
  • maybe.Single() gets you the value.
  • maybe.SingleOrDefault() gets you the value or null.
  • extension method maybe.None() is true if there's no value.

Creating a maybe can be done by:

  • object.AsMaybe(); - convert a reference type.
  • Maybe<int>.From(7); - works with value types.
  • Maybe<T>.Empty - a maybe without a value.

Maybe<T> has a ToString() method so you can write it to a log, an output stream or use in a string interpolation, and you will get the serialized value or "{no value}".

Try returning a Maybe<T> whenever you have a situation wehere there may be no value, instead of null. You may find that your bug count tends to diminish.

⚠️ **GitHub.com Fallback** ⚠️