For a little more comprehensive solution, you could check out the Introduce Null Object Refactoring. The basic mechanics of this refactoring is that instead of checking for nil
in the client code you instead make sure that the provider never produces a nil
in the first place, by introducing a context-specific null object and returning that.
So, return an empty string, an empty array, an empty hash or a special empty customer or empty user or something instead of just nil
and then you will never need to check for nil
in the first place.
So, in your case you would have something like
class NullUser < User
def name
return ''
end
end
However, in Ruby there is actually another, quite elegant, way of implementing the Introduce Null Object Refactoring: you don't actually need to introduce a Null Object, because nil
is already an object! So, you could monkey-patch nil
to behave as a NullUser – however, all the usual warnings and pitfalls regarding monkey-patching apply even more strongly in this case, since making nil
silently swallow NoMethodError
s or something like that can totally mess up your debugging experience and make it really hard to track down cases where there is a nil
that shouldn't be there (as opposed to a nil
that serves as a Null Object).