views:

36

answers:

2

I am tired of trapping for nil when looking for a dependent record when most of the time a return of 0 will do nicely. What sort of trouble am I creating for myself by adding "id" to the NilClass thus

class NilClass
  def id
    0
  end
end

What might the unintended consequences be? I know about exists?(), but somehow thought this might be cleaner.

Your thoughts?

+1  A: 

Won't this mean you will need to check for "id == 0" to confirm existence? Not to mention unintended consequences of overiding base Ruby functionality - it becomes really hard to predict behaviour of other libraries and core Rails APIs when you mess with language internals. Not saying it won't just work, but it's hard to be sure.

I would leave the default - it works quite nicely as Ruby allows "if object.association" expressions.

Toby Hede
+1  A: 

If you really have a problem with this, you should use referential integrity inside your database.

If you must call methods on nil which may or may not exist or throw some kind of error, you should use either a check a la

 > nil.id if nil
=> nil

or Object#try (which is part of ActiveSupport nowadays I believe?), be warned - I reckon it's kind of a code smell.

 > nil.try(:id)
=> nil 

That being said, it is less of a smell than modifying NilClass to do something unexpected, think of what a new developer who had to work on your project would expect.

Omar Qureshi
" think of what a new developer who had to work on your project would expect." OUTSTANDING question!
Paul
Omar - you pointed me in the right direction with Object#try. I think what I will wind up doing in those cases where I prefer zero to nil is write: "object.id.to_i"
Paul
I'm glad I helped you here, though, the real fix I reckon is the referential integrity fix! That way, you wont have to deal with non-existent objects unless if you have a one-to-one relation.
Omar Qureshi