The Tell, Don’t Ask (TDA) principle suggests that it is better to issue an object a command do perform some operation or logic, rather than to query its state and then take some action as a result.

It is related to the Flags Over Objects antipattern as well as the Anemic Domain Modelantipattern.

You can easily spot violations of TDA in code that queries or uses several properties of an object in order to perform some calculation.

This is especially problematic when the same kind of calculation is done in many places (violating the Don’t Repeat Yourself principle), but can represent a design deficiency even if it only occurs in one location in the current codebase.

// Violates TDA
public class CpuMonitor
{
public int Value { get; set; }
} public class Client
{
public void AlertService(List<CpuMonitor> cpuMonitors)
{
foreach (var cpuMonitor in cpuMonitors)
{
if (cpuMonitor.Value > )
{
// alert
}
}
}
} // Refactored
public class CpuMonitor
{
private readonly int _alertThreshold; public CpuMonitor(int alertThreshold)
{
_alertThreshold = alertThreshold;
} public int Value { get; set; }
public bool ExceedsThreshold { get { return Value >= _alertThreshold; } }
} public class Client
{
public void AlertService(List<CpuMonitor> cpuMonitors)
{
foreach (var cpuMonitor in cpuMonitors)
{
if (cpuMonitor.ExceedsThreshold)
{
// alert
}
}
}
} // Refactored Further
public class CpuMonitor
{
private readonly int _alertThreshold;
private readonly Action<CpuMonitor> _alertAction; public CpuMonitor(int alertThreshold, Action<CpuMonitor> alertAction)
{
_alertThreshold = alertThreshold;
_alertAction = alertAction;
} public int Value { get; set; }
public bool ExceedsThreshold { get { return Value >= _alertThreshold; } } public void Sample()
{
if (ExceedsThreshold)
{
_alertAction(this);
}
}
} public class Client
{
public void AlertService(List<CpuMonitor> cpuMonitors)
{
foreach (var cpuMonitor in cpuMonitors)
{
cpuMonitor.Sample();
}
}
}

In the example above, the first refactoring looks at the magic number representing the alert threshold, and moves this concept into the monitor itself.

This might not be worth correcting if this client code were the only instance of this behavior, but if you find repetition in this kind of code, follow the Don’t Repeat Yourself principle and consolidate it into a class (in this case, CpuMonitor).

The initial refactoring is still querying each monitor and then performing some action based on that query, and so is still asking, not telling.

The final refactoring moves the responsibility for sending alerts into the monitor itself, while still avoiding tightly coupling it to any particular alert implementation.

In this way, monitor remains loosely coupled from whatever alert implementation the system might have in place.

It’s not necessary to follow the “don’t ask” part of this principle to the extreme of eliminating all access to objects’ state.

In general, it’s ok to query an object for its state, provided the information isn’t being used to make a decision related to the object.

If it is, then that decision and any corresponding behavior should most likely be moved within the object itself.

Another consequence of violating TDA is that often magic numbers or business rules end up sprinkled throughout code that references object state, rather than embedded within the object itself or passed into the object as a defined and well-named construct (such as CpuAlertThreshold in the example above).

    class Program
{
static void Main(string[] args)
{
Person xiaoMing = new Person("小明");
xiaoMing.WhatToDo = "泡面";
new Bolier(, xiaoMing.DoSthUseHotWater).HeatUp(); Person daMing = new Person("大明");
daMing.WhatToDo = "洗脸";
new Bolier(, daMing.DoSthUseHotWater).HeatUp(); }
} public class Person
{
public string Name { get; private set; }
public string WhatToDo { get; set; }
public Person(string name)
{
Name = name;
} public void DoSthUseHotWater(Bolier bolier)
{
Console.WriteLine(string.Format("{0}用{1}度的水{2}", Name, bolier.WaterTemperature, WhatToDo));
}
} /// <summary>
/// 烧水壶
/// </summary>
public class Bolier
{
public int WaterTemperature { get; private set; }
private int necessaryWaterTemperature;
private Action<Bolier> completeAction; public Bolier(int necessaryWaterTemperature, Action<Bolier> completeAction)
{
this.necessaryWaterTemperature = necessaryWaterTemperature;
this.completeAction = completeAction;
} public void HeatUp()
{
while (WaterTemperature < necessaryWaterTemperature)
{
Console.WriteLine(string.Format("{0}-当前水温:{1}", DateTime.Now.ToString(), WaterTemperature));
Thread.Sleep();
WaterTemperature += ;
} completeAction?.Invoke(this);
}
}

随机推荐

  1. sql Left right join 多表 注意表的连接顺序

    多表左/右连接,表的连接顺序也可以影响查询速度 左连接时,应该把小表放在前面连接例子:A.B.C三表左连接情况1:A先和B连接,得到100条记录100条记录再和C左连接情况2:A先和C连接,得到50条 ...

  2. jvm常用参数设置 专题

    在jdk8中 -Xms2g不合法,能通过的:-Xms2G #!/bin/bash JAVA_OPTS="-Xms4G -Xmx4G -XX:+HeapDumpOnOutOfMemoryErr ...

  3. [解决方案]sql server复制需要有实际的服务器名称才能连接到服务器

    原文:[解决方案]sql server复制需要有实际的服务器名称才能连接到服务器 在配置数据同步的时候,要求相互同步的两台机器的数据库必须通过默认实例名称进行连接.如果你的默认实例已经删掉了,在当前实 ...

  4. ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区

    原文:ArcGIS for Desktop入门教程_第一章_引言 - ArcGIS知乎-新一代ArcGIS问答社区 1 引言 1.1 读者定位 我们假设用户在阅读本指南前应已具备以下知识: · 熟悉W ...

  5. 零元学Expression Blend 4 - Chapter 23 Deep Zoom Composer与Deep Zoom功能

    原文:零元学Expression Blend 4 - Chapter 23 Deep Zoom Composer与Deep Zoom功能 最近有机会在工作上用到Deep Zoom这个功能,我就顺便介绍 ...

  6. 零元学Expression Blend 4 - Chapter 2 入门界面简介

    原文:零元学Expression Blend 4 - Chapter 2 入门界面简介 在这篇教学我将会介绍Expression Blend 4的基本界面,虽然有些网站已经有做了介绍,为了整个教学的完 ...

  7. mysql多对一、多对多查询实践

    最近做的功能涉及这方面,算是练了一下. 首先多对一部分较简单.多的那一方表,多设置一个字段是少的那一方的id(主键). 具体查询时候关联查询即可. 可设置外键进行级联操作. 具体以后做到这个功能再更新 ...

  8. SignalR---DOTNET客户端

    原文:SignalR---DOTNET客户端 这里面有用到异步的相关知识,本人前几篇文章也简单的提到. SignalR客户端要寄宿在.NET的客户端,必须安装Microsoft.AspNet.Sign ...

  9. MySql5.7.11 for Windows 安装精简版(一)

    原文:MySql5.7.11 for Windows 安装精简版(一) 从官网下载压缩包,我下载的是64位的.解压. 精简: -Bin下只保留 mysqladmin.exe mysqld.exe my ...

  10. 年度调查 看看 2016 年 Go 语言调查结果

    Go 语言官方博客公布了 2016 年 Go 语言使用调查. 在 3,595 名被调查者中,89% 称他们在工作中或工作之外用 Go 编程:63% 称他们的工作是 Web 开发,但只有 9% 的人只从 ...