3 ms·
Such code is everywhere in the Ruby community and explicitly endorsed by many. I have never seen code like your second example in the wild, and it's far more co
by necubi 15y ago
Such code is everywhere in the Ruby community and explicitly endorsed by many. I have never seen code like your second example in the wild, and it's far more complicated than the idiomatic way of writing it:
if some_value
do_something
end
It's a core expectation of the language that !!nil_thing == false, so why violate it?
- Confusion 15y agoBecause 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.
- csallen 15y agoI 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.
- Confusion 15y agoI 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.
- aphyr 15y agoI 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.
- perfunctory 15y agoI actually agree with Confusion. All these implicit coercions _will_ bite you. Don't understand why his post is downvoted.