Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Don't Overload #nil?

  Paul Rosania        2011-11-10 10:50:22       2,785        0    

There’s a popular post on Hacker News about writing confident code by, among other things, overloading Object#nil? and returning “null objects” instead of nil itself.

DO NOT DO THIS.

In Ruby, all objects (except nil itself) coerce to the boolean value true. Your object will be nil and true at the same time. Bad things will happen. Your coworkers will cry. Sad people from around the world will ask bewildering questions on your mailing list.

Here’s what happens:

1
2
3
4
5
6
7
8
9
10
11
class NullObject
  def nil?
    true
  end
end

o = NullObject.new

o.nil?             #=> true, great.
!!o                #=> true. not so great.
puts "exists" if o #=> "exists". ut oh.

Do you write all your guards using if o.nil? Neither do I.

If you overload #nil?you will get burned. Please don’t.

Source:http://paul.rosania.org/writings/2011/11/09/dont-overload-nil/

RUBY  OBJECT  #NIL  OVERLOAD 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.