This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: The nil test
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
A post on ruby-talk today reminded me of something regarding nil and method chaining today. You sometimes see folks writing something like this:
if foo.nil? || foo.empty?
This happens because they quickly realize that if 'foo' is nil, then trying to call foo.empty? will fail because there's no such method .empty? for nil. However, that line can be reduced as follows:
if foo.to_s.empty?
This works because calling .to_s on nil returns "" (an empty String). Also note that calling .to_i on nil returns 0, which can come in handy.
Technically, my version is a bit slower. The former could, in theory be faster, since my version always calls .to_s. That overhead is extremely minimal (not that I have any benchmarks handy).
The real point I wanted to get to is that you should always, always, ALWAYS have unit tests that test nil values for your method arguments, even if it's just to verify that an error is raised. This will quickly weed out the "NoMethodError: undefined method ..." errors (the equivalent of everyone's favorite Java error, NullPointerException).