为此函数添加一个对象函数,让改对象带进函数所需要信息
getContact()
to
getContact(:Date)
动机
在改变方法之后,你获得更多的信息
一个参数不在函数中使用了
移除它

getContact(:Date)
to
getContact()
动机
一个参数不再使用还留着它干嘛?
某个函数即返回函数的状态值,又修改对象的状态
创建两个不同的函数,其中一个负责查询,另一个负责修改
getTotalOutStandingAndSetReadyForSummaries()
to
getTotalOutStanding()
SetReadyForSummaries()
动机
将有副作用的方法和没有副作用的方法分开
若干函数做了类似的工作,但在函数本体中却包含了不同的值
创建单一函数,已参数表达那些不同的值
fivePercentRaise()
tenPercentRaise()
to
raise(percentage)
动机
移除重复的代码提高灵活度
??一个函数,其中完全取决于参数值而采取不同的行为
针对该函数的每一个可能值,建立一个独立函数
void setValue (String name, int value) {
if (name.equals("height")){}
_height = value;
return;
}
if (name.equals("width")){
_width = value;
return;
}
Assert.shouldNeverReachHere();
}
to
void setHeight(int arg) {
_height = arg;
}
void setWidth (int arg) {
_width = arg;
}
动机
避免条件行为
在编译器进行检查
清晰的接口
你从某个对象支行取出若干值,将他们作为某一次函数调用时的参数
改为传递一整个对象
int low = daysTempRange().getLow();
int high = daysTempRange().getHigh();
withinPlan = plan.withinRange(low, high);
to
withinPlan = plan.withinRange(daysTempRange());
动机
使参数列表在变化的时候具有鲁棒性
使代码更与易读
在代码中移除相似的重复的代码
消极的 : 增加了函数参数在调用时的依赖
对象调用某个函数,并将其所得的结果作为参数,传递给另一个函数。而接受该参数的函数本身也能够调用钱一个函数
将函数接受者去除该项参数,并直接调用前一个函数
int basePrice = _quantity * _itemPrice;
discountLevel = getDiscountLevel();
double finalPrice = discountedPrice (basePrice, discountLevel);
to
int basePrice = _quantity * _itemPrice;
double finalPrice = discountedPrice (basePrice);
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-89441-20.html
理智理智