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. WCF SOAP用法

    基本思路 1.新建一个WCF服务库2.在客户端引用处右键,添加服务引用   点击发现,选择目标服务设置好命名空间   可以在高级一栏里面,设置详细信息   点击确认,添加服务引用 3.在客户端自动生成 ...

  2. wpf border内部元素内边角溢出问题 裁剪效果

    效果图 <Grid> <Border BorderThickness=" BorderBrush="#3c4d72" CornerRadius=&quo ...

  3. XF 标签和文本控件

    <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http:/ ...

  4. wpf 绑定表达式和手动更新源

    <Window x:Class="BindingExpressionExam.MainWindow"        xmlns="http://schemas.mi ...

  5. WPF 数据模板使用值转换器

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  6. .NET与Java互通AES算法加密解密

    /// <summary>AES加密</summary> /// <param name="text">明文</param> /// ...

  7. 关于SetLength报Out of memory的研究及解决办法

    关于SetLength报Out of memory的研究及解决办法 最近在做一个GIS系统, 在读GIS数据时采用了动态数组,突然读一个数据时SetLength报错!Out of memory 仔细研 ...

  8. 開發PlainTasks與JSON的插件

    PlainTasks 是款很有名的任務管理插件,具體的介紹在這裡. 我最近的工作作務,是開發一款插件,能實現 JSON 文件到 todo 類文件的轉換. JSON 的格式是這樣的 1: { 2: &q ...

  9. 静态编译 Qt 5.6

    源码下载 Qt git地址:git://code.qt.io/qt/qt5.git 推荐用 SourceTree 客户端来克隆源码 准备工作 系统 Windows 7 或者 Windows 10 编译 ...

  10. Linux升级OpenSSL版本

    安装nginx的时候,出现了这样的问题: nginx : Depends: libssl1.0.0 (>= 1.0.2~beta3) but 1.0.1f-1ubuntu2.11 is to b ...