2011年01月12日 at 8:29 am
#1304
Member
我很难理解tell,don’t ask这个原则
我看了在2L给出的文章,
That is, you should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do
使外界能了解自己的状态不正是对象的职责吗?不知这个理解哪里有误?
不过我猜想是否这样:
首先,ask没问题,可是不该以ask的结果为依据对其tell
然后,”ask,decide,then tell”针对的是对象职责范围内的逻辑
我想到个例子:
if(someControl.isVisible())
someControl.hide();
就是对象的职责外泄,因为”在已经隐藏的情况下无须调用hide”是Control自然该管的,正确的做法是:
someControl.hideIfVisible();
而同样是”ask,decide,then tell”,却不可能将
if(someNumber.isLargerThan(100))
someNumber=100;
敛为Number.truncateIfLargerThanOneHundred供人调用,因为100这个数字在只谈论Number的时候是个magic number,它的语义是在Number以外才得以实现的