Tell Don't Ask and Mock Objects(转载)

Tell Don't Ask and Mock Objects

In my experience, object-oriented code is easier to understand and maintain if it is written in a "Tell, Don't Ask" style. In this style, objects make decisions using only the information that they hold internally or that they receive as message parameters; they do not make decisions using information that is held by other objects. That is, objects tell each other what to do by sending commands to one another, they don't ask each other for information and then make decisions upon the results of those queries.

The end result of this style is that it is easy to swap one object for another that can respond to the same commands but in a different way. This is because the behaviour of one object is not tied to the internal structure of the objects that it talks to.

How does that apply to Mock Objects? If objects interact by sending each other commands, their public interfaces provide no methods that let you interrogate their state. The only way to observe the behaviour of an object is to see how it affects the state of its world by sending commands to other objects. And that's what Mock Objects let you do.

The extreme opposite of the "Tell, Don't Ask" style is "train-wreck" code that contains lots of statements like "object.getPart().getSubpart().getAttribute()" and "object.getPart().getSubpart().setAttribute(x)". In coding style the implementation of one object is coupled to the structure of its neighbours and its neighbours' neighbours, and so it is difficult to replace its neighbour with one that is implemented differently.

This style of code is hard to test with Mock Objects. You find yourself creating lots of mock objects that only exist to let the object under test reach the objects that it actually uses. That's a strong sign that the code needs refactoring: you can simplify the code by introducing new methods in the immediate neighbours of the object under test.

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值