Hacker News new | ask | show | jobs
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.
2 comments

I disagree. I find it most natural to assume nil and false are negatively charged because that's how the language is defined. If I want to differentiate between nil and false, I use .nil? or == false.

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.

I agree with aphyr's response to you. This has never been a problem for me. I think your issue is that you consider an empty string to be a sensible default representing false or nil.
I fully agree that those sane defaults indeed aren't right for representing false or nil. What I'm arguing is rather the reverse: nil is often initially used as an (insane?) default and that is later changed without updating all related checks (because they don't stick out and demand attention, which makes them easy to overlook or 'overthink'), which causes bugs.