动机
当一个表达式难以理解时
你能有一个临时变量声明不止一次,但是它不是循环体中的变量或者要被存储的变量
double temp = 2 * (_height + _width);
System.out.println (temp);
temp = _height * _width;
System.out.println (temp);
to
final double perimeter = 2 * (_height + _width);
System.out.println (perimeter);
final double area = _height * _width;
System.out.println (area);
动机
变量不应该有多次的声明
使用临时变量在两次不同的地方,是阅读者十分迷惑的
下的代码将对参数进行了赋值
int discount (int inputVal, int quantity, int yearToDate) {
if (inputVal > 50) {
inputVal -= 2;
}
}
to
int discount (int inputVal, int quantity, int yearToDate) {
int result = inputVal;
if (inputVal > 50) {
result -= 2;
}
}
动机
改变内部的对象时可以的,但是不能将这个对象指向别的对象
参数的作用仅仅是表达传递对象
将这个函数放进一个单独的对象,如此一来局部变量就变成对象内部的字段,然后你可以在同一个对象中将这个大型函数分解为多个小型函数
class Order...
double price() {
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation;
...
}
to
class Order...
double price(){
return new PriceCalculator(this).compute()
}
}
class PriceCalculato...
compute(){
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
// long computation;
return ...
}
动机
当一个方法有很多的本地变量时进行分解时不容易的
它的样本本不应该这样的重构,但是为显示这样做的方法
Class Account
int gamma (int inputVal, int quantity, int yearToDate) {
int importantValue1 = (inputVal * quantity) + delta();
int importantValue2 = (inputVal * yearToDate) + 100;
if ((yearToDate - importantValue1) > 100)
importantValue2 -= 20;
int importantValue3 = importantValue2 * 7;
// and so on.
return importantValue3 - 2 * importantValue1;
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/tongxinshuyu/article-89441-7.html
大陆迟早要乱的
#fx_4walls#热门
咬了伊拉克还理直气壮的威胁不让人家找帮手打狗