(1)Separate Query form Modifier 将查询函数和修改函数分离
如果某个函数只向你提供一个值,没有其它任何副作用(连带关系)。那么你就可以任意调用这个函数值。如果某个函数既返回对象状态值,又修改对象状态。则
需要分离这两个函数。
(2)Parameterize Method 令函数携带参数
若干函数做了类似的工作,但在函数体中却包含不同的值,需要建立单一的函数,以参数表达那些不同的值
Class Employee{
public void tenPercentRaise(){
salary*0.1;
}
public void fivePercentRaise(){
salary*1.05;
}
}
=》替换
Class Employee{
public void raise(double factor){
salary*factor;
}
}
(3) Replace Parameter with Explicit Methods 以明确的函数取代参数
这个和Parameterize Method 正好相反
如果某个参数有离散取值,而函数又以条件式检查这些参数,并且根据不同的参数作出不同的反应。
public void setValue(String name,int value){
if("weight".equals(name)){
_weight = value;
}
if("height".equals(name)){
_height = value;
}
}
=》替换
public void setWeight(int value){
_weight = value;
}
public void setHeight(int value){
_height = value;
}
(4)Preserve whole Object 保持对象完整
有时候将来自同一个对象的若干数据项作为参数,传递给某个函数。这样做的问题,万一新的调用者需要新的数据就的修改原来的函数
int low =dayRang.getLow();
int high =dayRang.getHigh();
widthPlan = plan.widthPlan(low,high);
=》替换
widthPlan = plan.widthPlan(dayRang);
(5) Replace Parameter with Methods 以函数取代参数
对象调用某个函数,并将结果作为传递给某个函数。而接受该参数的函数也有能力调用这个前一个函数
int basePrice = _quantity*_itemPrice;
disCountLevl = getDisCountLevl();
double findPrice = disCountPrice(basePrice, disCountLevl);
=》替换
int basePrice = _quantity*_itemPrice;
double findPrice = disCountPrice(basePrice);
对getDisCountLevl()的调用在disCountPrice函数里进行。
(6) Introduce Parameter Object (引入参数对象)
某些参数总是同时出现 比如startDate endDate 以一对值表示一个范围。我们称之为数据泥团Data Clump。把这些参数组织在一起
double getFlowBetween(Date startDate,Date endDate){
.....
}
=》替换
public class DateRang{
private final Date startDate;//设置为final是只能是构造函数才能初始化
private final Date endDate;
public DateRang(Date startDate,Date endDate){
this.startDate = startDate;
this.endDate = endDate;
}
public Date getStartDate(){
return startDate;
}
public Date getEndDate(){
return endDate;
}
}
double getFlowBetween(DateRang dateRang){
.....
}
(7)Replace Error Code with Exception 以异常取代错误代码
某个函数返回一个错误的编码 -1 以表示返某种错误的情况。当一个错误发生时,并不一定要知道如何处理,只需要让调用者知道这个错误。而调用者可能将这个
错误沿着调用链(call chain)传递下去。
int withdraw(int amount){
if(amount > _blance){
return -1;
} else {
_blance -= amount;
return 0;
}
}
=》替换
void withdraw(int amount) throws BalanceException{
if(amount > _blance){
throw new BalanceException();
} else {
_blance -= amount;
return 0;
}
}
(8) Replace Exception with Test 以测试取代异常
面对一个调用者可以预先加一个测试条件,如果你抛出一个异常。而这个异常对你没有任何意义。
double getValueForPeriod(int periodIndex){
try{
return _varArray[periodIndex];
}catch(ArrayIndexOutOfBoundException ex){
return 0;
}
}
=》替换
double getValueForPeriod(int periodIndex){
if(periodIndex >=_varArray.length){ return 0; }
return _varArray[periodIndex];
}
总结:异常只用来处理异常、罕见的行为,也就是那些产生意料子外的行为,而不能做为条件检查的替代品。
(8) Replace Constructor with Factory Method 以工厂函数取代构造函数
332页
