Getting rid of NullReferenceException
NullReferenceException is one of the most common exceptions we face when developing systems. This kind of exception is raised when trying to access some property or value from an object that is null.
We as developers sometimes forget to cover scenarios where the information could not exist, for example, when we try to recover a resource from a database through some unique id and this resource does not exists.
Let’s see how can we minimize the chances of this happen by “forcing” yourselves to deal with those kinds of scenarios by implementing the Maybe monad.
What is Maybe?
In a nutshell, Maybe is an artifact from the functional programming world that basically represents the result of a process that could go wrong and return no value. It wraps a value inside a structure that you can only access through function invoking.
In other orders, we must pass two functions in order to access the value, one to deal with the presence of the value and one to deal with its absence. It could look cumbersome at first but after we see some code everything will be more clear. I will show you the implementation in C# but we could adapt it easily to any language:
Note that we are using generics (<T>), so we can wrap any value inside this class. Inside the Match
method is where the magic happens. The some
function will be invoked with the value itself if we have some value, otherwise, the none
function will be invoked.
Using the Maybe
In order to use the maybe structure, I will “simulate” a customers repository layer that retrieves a customer by its id:
The method does not return a plain Customer
as we usually see, instead, it returns a Maybe
of Customer
, indicating that we could have a Customer
or not. With this single change, when we call this method, GetCustomerById
, we are “forced” to provide a function to deal with the two scenarios, one if the customer exists and one if not:
When we found the customer we just return it, otherwise, we throw an exception with a message that the customer was not found. With the maybe structure, we guarantee that will never have a null reference exception when trying the access the Customer
returned by the GetCustomerById
method, really cool right?
This post briefly covers the full power of the Maybe monad, if you would like to know more I recommend this gist.
That’s all for today, folks. I hope that this article has helped you in some way.
Take care and happy coding!