New account registration is temporarily disabled.
0 reviews
  • Add Review
  • Subscribe
  • Nominate
  • Submit Media
  • RSS

Use of the Maybe Monad in Metis

One of the most obnoxious errors one runs into when programming in C# is the dreaded NullReferenceException, which arises from attempting to use an object when you really have a null reference. The problem is that most methods which return objects will silently return null if the operation fails or produces unexpected output, and a NRE won’t be thrown until a property or method is called on that reference. In this way, null references can quietly leak throughout your program and propagate, filling it with time bombs ready to go off.

The other problem is that a lot of C# programmers (myself included, until recently) intentionally return null references to signify a failed operation. Though there’s nothing wrong with this, it’s very easy to forget to check if the result you received was null, and this is how null references can unintentionally pervade a system. Now you don’t know what’s supposed to be null and what’s not.

The solution we’re using in Metis is the Maybe monad. A Maybe<T> is an object which might contain an object of type T, or it might not. Thus, when a method returns a Maybe<T>, what that’s saying is that the returned value might not actually have a value, forcing you to check whether or not it does. Although it’s functionally the same as either returning a reference or null, it presents a few advantages.

Firstly, because Maybe<T> is in the return type, type safety prevents you from passing it to a method expecting a T without first checking the value.

Secondly, it has a psychological benefit: by establishing a protocol where methods which might not return a value will always return a Maybe<T>, this ensures that any method which is guaranteed to return a value will not return a Maybe<T>. In essence, what this means is that any method whose return type is not Maybe<T> can be safely used without null checking.

Because of this, any null reference which is spotted floating through the system is guaranteed to be an error, since nulls are never intentionally returned.

Sound handy? It is! You can pick up an implementation of Maybe<T> as well as a rundown on how to use it here: http://mikehadlow.blogspot.com/2011/01/monads-in-c-5-maybe.html