K
Klaus Stein
As far as I understand the whole discussion some wish this behaviour to beJohn Carter said: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.
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?
Klaus Stein