The Null Object Pattern for Users
The Null Object Pattern certainly isn’t a new idea, but it’s simple and can really help clean up some code, so I thought I’d share an example.
Background
Our login system is based off of acts_as_authenticated, but very few of our pages require a user to be logged in. We want to find out about the current user, but first we need to make sure they are logged in, otherwise current_user will return nil and you’ll end up with a NoMethodError. So we end up with a lot of code that looks like this:
Not too bad, but this pattern shows up all the time in our code.
A Solution
Null Object to the rescue! The idea is dead simple: instead of returning nil if the user isn’t logged in, just return a instance of a new class – NilUser.
Now we just update current_user to return a NilUser if the user isn’t logged in:
Now all of our conditionals are shortened to a single condition, much nicer.
Final Words
If you try something along these lines, just remember to add corresponding methods to your new class for each public method of the class you are potentially replacing. If you felt like living dangerously you could even add a method_missing to your nil class that returned nil on any undefined methods and only define methods where you wanted a different return value – but this could easily turn into a debugging nightmare.
Also make sure to update any code where you depended the returned object being nil – for example:
will be broken. You might even need to add another method to your Null Object class, something like:
In our case we can use logged_in? if all we want to know is whether a user is logged in or not.
That’s all there is to it! While not something you’d want to use all the time, when used appropriately it can help cut a lot of repeated code in your conditionals and improve the code’s readability.
Next Post: A little meta-programming to simplify the nil class definition