From: Robert Klemme Date: 2005-05-19T20:30:14+09:00 Subject: Re: RCR 303: nil should accept missing methods and return nil Klaus Stein wrote: > John Carter wrote: >> A very simple and generic way of improving the reliability of Ruby >> programs is to implement the NullObject pattern by allowing nil to >> accept all and every method instead of throwing a NoMethodError. >> > As far as I understand the whole discussion some wish this behaviour > to be able to do things like > > obj.meth1().meth2().meth3() > > which should not break if meth2 for some cause returns nil. > > On the other hand many people claim this will hide errors (I agree > here). It seems there are two kinds of nils: expected and unexpected > ones. > > So why dont we deal with the expected ones seperately: > > ========================================================== > class Object > def nil_friendly > self > end > end > > class NilClass > def nil_friendly > Blackhole.instance > end > end > > class Blackhole > include Singleton > def method_missing( sym, *args) > nil > end > end > > ## Now this works: > > obj.meth1().meth2().nil_friendly.meth3() > ========================================================== > > So by inserting .nil_friendly (choose a better/shorter name for this) > you _explicitly_ tell that you don't care if nil ist returned. > > This will not break any existing code, will not hide errors, but gives > shorter code without explicit ifs. > > Comments? What about #nil? robert