提取[常客积点计算]代码
首先我们需要针对[常客积点计算]这部分代码(以下粗体部分)运用Extract Method(110)重构准则:
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = "Rental Record for * " + getName() + "\n";
while(rentals.hasMoreElements()) {
Rental each = (Rental)rentals.nextElement(); //取得一笔租借记录
// add frequent renter points(累加常客积点)
frequentRenterPoints ++;
if((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) &&
each.getDaysRented() > 1)
frequentRenterPoints ++;
result += "\t" + each.getMovie().getTitle() + "\t" +
String.valueOf(each.getCharge()) + "\n";
totalAmount += each.getCharge();
}
// add footer lines(结尾打印)
result += "Amount owed is " + String.valueOf(totalAmount) + " \n";
result += "You earned " + String.valueOf(frequentRenterPoints) +
"frequent renter points";
return result;
}
再一次我又要寻找局部变量。这里再一次用到了each,而它可以被当作参数传入新函数中。另一个临时变量是frequentRenterPoints。本
例中的它在被使用之前已经先有初值,但提炼出来的函数并没有读取改值,所以我们不需要将它当作参数传进去,只需对它执行[付添赋值操作](appending assignment,operator+=)就行了。
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = "Rental Record for * " + getName() + "\n";
while(rentals.hasMoreElements()) {
Rental each = (Rental)rentals.nextElement(); //取得一笔租借记录
frequentRenterPointers += each.getFrequentRenterPoints();
result += "\t" + each.getMovie().getTitle() + "\t" +
String.valueOf(each.getCharge()) + "\n";
totalAmount += each.getCharge();
}
// add footer lines(结尾打印)
result += "Amount owed is " + String.valueOf(totalAmount) + " \n";
result += "You earned " + String.valueOf(frequentRenterPoints) +
"frequent renter points";
return result;
}
class Rental...
int getFrequentRenterPoints() {
if((getMovie().getPriceCode() == Movie.NEW_RELEASE)
&& getDaysRented() > 1)
return 2;
else
return 1;
}