|
|
|
|
|
by Confusion
5332 days ago
|
|
Because when you write if !some_value
do_something
end
you often don't actually want it to be executed when some_value is nil instead of false. And when it is, you go scratching your head and searching where some_value came from, to discover some silly typo.In some ways, the reverse is even worse: when you write if some_value
do_something
end
and you change some_value from nil to some sensible default like '', you will forget to update this clause and you will not understand why the code is being executed. If you use if !some_value.nil?
do_something
end
you don't have that problem, because the nil-test sticks out like a sore thumb. |
|
Somehow this has never been a problem for me in eight years and hundreds of thousands of Ruby lines--but every programmer is different, and I'd like to hear other views.
change the base case of some_value from nil to 0, nil to NullObject
change some_value from nil to some sensible default like ''
What, what, what are you doing? Who uses an empty string to mean "uninitialized"? Nil and {0, "", etc) have very different semantic meanings. How would you discriminate between the default "" and a user-submitted ""? If you mean to check whether it has changed from the default, compare it to a default constant. If you mean to check emptiness, use #empty? or #blank?. I read these kinds of explicit .nil? checks as fighting the language, and in some ways, a violation of the cultural contract in Ruby and Lisp around truth charge.