In Java we all dread the dreaded NullPointerException of dread.
In Ruby nil is a class and we can do something about it.
Monkeypatching core classes is of course a Bad Thing(tm) but this particular one
should* break nothing since we’re adding a self contained method to a class that doesn’t alter the functioning of any of the other methods on the class. Furthermore we’re adding something that simply makes sense, so when you call it sensible things happen. Now, as with most
innovative thoughts, it isn’t.
According to _why it’s been brought up by far more knowledgeable Ruby geeks than I:
Jim Mernard,
Dave Thomas, and
Dan Fitzpatrick have all argued for this. Others have argued against. The others all work for The Man and are just trying to put you down.
Behold, the glory of nil.empty?
class NillClass
def empty?
return true
end
end
Oooh ahh… Bow before its glory! Bow I say!
Do you not see? NilClass is the void. It is nothingness incarnate. You may debate if it is really false, since how can nothing be true or false, but it is most assuredly empty, for how could nothingness ever contain something? Now you never need to @#$% check if a thing exists or not before checking if it’s empty.
More lately people including _why have been arguing for nil.blank? This is, of course, craziness. While I encourage such insanity in _why (it’s what makes him great) it is impossible. Nothing can not be blank, for it has no form, no surface, and only things can be blank. Nothing is neither blank, nor non-blank.** Rails has, of course, incorporated nil.blank? because they’d monkeypatch their grandmothers if they could figure out how. Personally, while I love this particular monkeypatch I don’t think any core classes should ever be monkeyatched in a distributed library or app, but YOUR app, that other apps don’t use as a foundation…. monkeypatch whatever-the-hell you want, just be sure to document it well.
*I say “should break nothing” but there is, of course, being stupid and using the unexpected, and slow, thrown exception to change the flow instead of checking for nil.
** Yes, the antonym for blank is “full”, but if you ask me, that makes no sense.
P.S. It’s a really good thing that Java isn’t monkeypatchable because if it was java.util.Calendar would be monkepatched a new and incompatible way in every single library out there because we all hate its @#$% guts. Use Joda Time instead.