我看到的最多被违反的原则是“命令,不要去询问(Tell, Don’t Ask)”原则。这个原则讲的是,一个对象应该命令其它对象该做什么,而不是去查询其它对象的状态来决定做什么(查询其它对象的状态来决定做什么也被称作‘功能嫉妒(Feature Envy)’)。
这篇文章里有个很生动的例子,我至今记忆犹新:
if (person.getAddress().getCountry() == “Australia”) {
这违反了得墨忒耳定律,因为这个调用者跟Person过于亲密。它知道Person里有一个Address,而Address里还有一个country。它实际上应该写成这样:
if (person.livesIn(“Australia”)) {
非常的明了。今天我又看到一个关于“Tell, Don’t Ask”原则的文章,里面提供了4个关于这个原则的例子,都很有价值。
例一
不好:
<% if current_user.admin? %><%= current_user.admin_welcome_message %><% else %><%= current_user.user_welcome_message %><% end %>
好:
<%= current_user.welcome_message %>
例二
不好:
def check_for_overheating(system_monitor)if system_monitor.temperature > 100system_monitor.sound_alarmsendend
好:
system_monitor.check_for_overheatingclass SystemMonitordef check_for_overheatingif temperature > 100sound_alarmsendendend
例三
不好:
class Postdef send_to_feedif user.is_a?(TwitterUser)user.send_to_feed(contents)endendend
好:
class Postdef send_to_feeduser.send_to_feed(contents)endendclass TwitterUserdef send_to_feed(contents)twitter_client.post_to_feed(contents)endendclass EmailUserdef send_to_feed(contents)# no-op.endend
例四
不好:
def street_name(user)if user.addressuser.address.street_nameelse'No street name on file'endend
好:
def street_name(user)user.address.street_nameendclass Userdef address@address || NullAddress.newendendclass NullAddressdef street_name'No street name on file'endend
好的面向对象编程是告诉对象你要做什么,而不是询问对象的状态后根据状态做行动。数据和依赖这些数据的操作都应该属于同一个对象。
命令,不要去询问!
分享到:
相关推荐
从用户的Facebook NewsFeed隐藏权力的破坏者游戏。 支持语言:English (United States)
show and tell
Steal This File Sharing Book: What They Won't Tell You About File Sharing 有问题,我的QQ:571669275
Steal This Computer Book 3: What They Won't Tell You About the Internet 有问题,我的QQ:571669275
load design -d oadata 刷新数据库命令 sh ta 刷新当前 重启整个服务器:RES SER [在后台远程重启服务器] 重启HTTP: Tell HTTP Quit [关闭HTTP]-> Load HTTP [启动HTTP] 重启HTTP: Tell HTTP Restart [重启HTTP] ...
仿照泰豪网站首页,整个首页包括轮播图和动画,http://www.tellhow.cn/,这是网站首页,效果一模一样,练习编写,如果有兴趣可以下载看看,引入了轮播图框架和动画框架
完整工程案例:图像描述---Show and Tell: A Neural Image Caption Generator,基于Inception V3与LSTM实现图像描述,运行环境(Tensorflow1.0及以上,Python3.6)
Show and Tell_ Lessons learned from the 2015 MSCOCO Image Captioning Challenge
Tellus公司是加拿大最主要的通信公司之一,它向全球客户提供通信产品和服务,将加拿大与整个世界连接起来。Tellus电子商务分部与Sun的工程师一道,创建了一个以Web为中心的专门供服务提供商(SP)应用的解决方案。这是...
Unit Tell me when the pain startedPPT教案.pptx
I have 1TB disk, but the system tell me it was 931GB disk
浙江杭州下城区2019-2020学年第一学期教学质量监测九年级语文试题及答案.pdf
From Show to Tell A Survey on Image Captioning.zip
教育精品资料
05 show attend and tell讲解
完整工程案例:图像描述---Show and Tell: A Neural Image Caption Generator,基于Inception V3与LSTM实现图像描述,运行环境(Tensorflow1.0及以上,Python3.6)
广东省博罗县泰美中学七年级英语下册 Module 6 Unit 1 Could you tell me how to get to the National Stadium导学案(无答案)(新版)外研版
Telltale 音乐提取器 版本 1.5.6 本尼博伊 一个程序,可让您从 Telltale Games 开发的游戏中翻录音乐。 这包括其他人使用 Telltale 引擎制作的游戏,例如 Skankape Games 的 Sam & Max Save the World。 此版本中的...
Description : Function to tell whether the disk is smaller than SMALL_DSK_BYTES.