Tell,Don’t Ask!

       我看到的最多被违反的原则是“命令,不要去询问(Tell, Don’t Ask)”原则。这个原则讲的是,一个对象应该命令其它对象该做什么,而不是去查询其它对象的状态来决定做什么(查询其它对象的状态来决定做什么也被称作‘功能嫉妒(Feature Envy)')。
       例子:
       if (person.getAddress().getCountry() == "Australia") { 
               //违反了迪米特法则,调用者与Person关系太近,知道Person有
              //address,而且address中有country
       } 
       应改为:
       if(person.livesIn("Australia")){
           //operation
       }

一篇关于Tell,Don't ask 的文章中的例子:

EXAMPLE 1

 Not so good:

 <% if current_user.admin? %>	
        <%= current_user.admin_welcome_message %>
 <% else %>
        <%= current_user.user_welcome_message %>
 <% end %>

Better:

 <%= current_user.welcome_message %>

EXAMPLE 2

Not so good:

  def check_for_overheating(system_monitor)
      if system_monitor.temperature > 100
         system_monitor.sound_alarms
      end
  end

Better:

  system_monitor.check_for_overheating

  class SystemMonitor
       def check_for_overheating
           if temperature > 100
              sound_alarms
           end
       end
  end
          好的面向对象设计是告诉对象做什么,而不是查询一个对象状态然后根据状态采取动作。数据和依赖这些数据的动作都应该属于同一个对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值