Have you ever had to turn the following:
Into some awful
nil check like this?
post.author.name if post.author #or post.author && post.author.name #or post.author.name unless post.author.nil? #or post.author ? post.author.name : 'O Nameless One'
This code does not inspire to say the least.
Today I learned of the black hole null object from Avdi Grimm and it really made my day. Where has this been all my life? This is a simple class, which always returns itself, and returns true for
class NullObject def method_missing(*args, &block) self end def nil?; true; end end
NullObject returns self from every call, an entire chain of calls silently fails:
n = NullObject.new n.these.are.a.chain.of.calls => #<NullObject>
This is truly marvelous when combined with a
def Maybe(value) value.nil? ? NullObject.new : value end
Now our hesitant code can become:
The only problem is any object, by itself, will evaluate to truthy. You must use
.nil? in conditionals (or create more methods, such as
author = Maybe(post.author) if author.nil? # do something intelligent end