After reading about delegation and the laws of demeter I have been
attempting to use the “delegate” method in Rails to avoid situations
where I would have to write…
@account.account_holder.name
and risk a NoMethodError if @account.account_holder is nil
Delegate looked ideal as it allows me to specify
@account.account_holder_name and delegate that to AccountHolder and
alias :name to :account_holder_name.
However, it seems by this point to have already become slighty ugly
code (delegating and then aliasing methods) and to top it all if it
appears that delegate doesn’t return nil, but still raises an
exception.
As the laws of demeter seem quite sound and a good principal to
follow, is there any reason that we shouldn’t be using “delegate”? and
if we are supposed to use it why doesn’t it return something safe like
nil? (or does it just need a patch?)
Are there any other techniques I can use to avoid having to traverse
potentially nil relationships to retrieve attributes?
Refs:
http://caboo.se/doc/classes/Module.html#M003481
http://quotedprintable.com/articles/2006/12/22/delegation-and-demeter-in-rails
http://brian.maybeyoureinsane.net/blog/2006/12/15/law-of-demeter-or-how-to-avoid-coding-yourself-into-a-corner-in-rails/