A functional alternative to returning null

Last week I wrote about alternatives to returning null. There was however one alternative that I left out, the Maybe functor.

The reason I left it out last week was that I hadn’t had the time to read up on it properly. Now that I do have read up on it, and had some time to implement it and play around with it a bit, it is time to write a bit about it.

The Maybe functor, or Maybe monad, is a concept that is used in many functional languages such as Haskell, Scala, and F# (although it is called option in F#), and also in Rust (see docs).

In C# there is no support for the Maybe functor in the language itself, you have to implement it yourself. What you want to create is a generic class, Maybe<T>, that may, or may not, have an Item of type T associated to it. A method that maybe returns an int can look like this:

public Maybe<int> Parse(string s)
{
  if (int.TryParse(s, out var i))
    return new Maybe<int>(i);

  return new Maybe<int>();
}

As can be seen above the method signature makes it very clear that the parsing might fail, this makes it really hard for the caller to forget to cover the error case:

var parsed = Parse("42");
if (parsed.HasItem)
  Console.WriteLine($"The value was successfully parsed as {parsed.Item}");
else
  Console.WriteLine("Parsing failed");

Personally I like this alternative, but I am unsure how well it will fly with other C# developers.

If you like to read more about it, and see how it can be implemented, I strongly recommend you to visit Mark Seeman’s excellent blog. He writes about the Maybe functor in http://blog.ploeh.dk/2018/03/26/the-maybe-functor/

Rulla till toppen