【译】笛米特法则

Sunday, July 25, 2010

原文:http://rails-bestpractices.com/posts/15-the-law-of-demeter

根据笛米特法则,一个模型应该只和它关系最近的关联通信,尽量不和关联的关联and关联的属性通信,这是个松耦合的例子

丑陋的...

class Invoice < ActiveRecord::Base
  belongs_to :user
end

<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>

在这个例子中, invoice模型对象调用了关联模型user的属性(名字, 地址和电话),这样违反了笛米特法则,我们应该添加一些封装方法进来

重构...

class Invoice < ActiveRecord::Base
  belongs_to :user
  delegate :name, :address, :cellphone, :to => :user, :prefix => true
end

<%= @invoice.user_name %>
<%= @invoice.user_address %>
<%= @invoice.user_cellphone %>

很幸运,rails提供了这样一个委托方法,
这是一个DSL方式生成的封装方法,除了松耦合,委托(delegate)也防止了一个空对象被方法调用产生的错误,如果你加上选项
:allow_nil => true的话

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top