From: "David A. Black" Date: 2009-09-07T19:36:58+09:00 Subject: Re: Type checking function parameters Hi -- On Mon, 7 Sep 2009, Bill Kelly wrote: > > From: "Josh Cheek" >> >> Personally, I've been wondering what would happen if nil just returned nil >> for every undefined method. Essentially, instead of always having to put >> if x && x.value && x.value > 3 >> >> I could just put >> if x.value > 3 >> >> because if x was nil, then nil.value would be nil, and nil.>(3) would be >> nil. >> >> I just wonder if this would break things, or is a naive question to ask, so >> I've been a little silent about it. But it keeps coming back to me, because >> a lot of edge case errors revolve around nil not responding to methods. > > Can if you want: > > irb(main):022:0> class NilClass > irb(main):023:1> def method_missing(*args) > irb(main):024:2> nil > irb(main):025:2> end > irb(main):026:1> end > > irb(main):027:0> nil.foo.bar > => nil > irb(main):028:0> nil > 3 > => nil > > etc. > > Objective-C works that way. > > The downside is, for cases where you are calling a method > on an object you really did not want or expect to be nil, > you no longer get the error at the point of that method > call. To me having code fail fast in error conditions is > more important, so I don't patch NilClass as shown above. > But, ruby allows it if you really want. I wouldn't do it, though, even if I really wanted it :-) There may be code in the standard library, or elsewhere, that's relying on the documented behavior of nil. David -- David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com Ruby/Rails training, mentoring, consulting, code-review Latest book: The Well-Grounded Rubyist (http://www.manning.com/black2) September Ruby training in NJ has been POSTPONED. Details to follow.