我看到的最多被违反的原则是“命令,不要去询问(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