博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
命令,不要去询问(Tell, Don’t Ask)”原则
阅读量:6921 次
发布时间:2019-06-27

本文共 1516 字,大约阅读时间需要 5 分钟。

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

好的面向对象编程是告诉对象你要做什么,而不是询问对象的状态后根据状态做行动。数据和依赖这些数据的操作都应该属于同一个对象。

命令,不要去询问!

转载于:https://www.cnblogs.com/secbook/archive/2012/08/02/2655149.html

你可能感兴趣的文章
配置环境变量
查看>>
[K/3Cloud]创建一个操作校验器
查看>>
vue filters过滤器的使用
查看>>
国防军工企业信息化与信息安全概要
查看>>
iOS 7 新版微信 URL 不支持跳转 App Store 的解决方案
查看>>
IOS学习之UINavigationController详解与使用(一)添加UIBarButtonItem
查看>>
MFC CWnd
查看>>
ios10 app无法联网
查看>>
小记1
查看>>
JS function类型
查看>>
resize和reserve的区别
查看>>
NEWBE CRALWER 产品需求文档
查看>>
CRC校验和网络通信中writen、readn函数
查看>>
【网络编程/C++】修改本机ip地址
查看>>
匿名类型Study
查看>>
docker相关配置
查看>>
支持向量机(svm)
查看>>
Linux系统源码安装过程中的prefix选项
查看>>
POJ2479&&POJ2593 Maximum sum&&Max Sequence(最大连续和)
查看>>
半透明效果的UIToolbar
查看>>