Customer.statement():
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
Enumeration rentals = _rentals.elements();
String result = "Rental Record for * " + getName() + "\n";
while(rentals.hasMoreElements()) {
double thisAmount = 0;
Rental each = (Rental)rentals.nextElement(); //取得一笔租借记录
thisAmount = each.getCharge();
// add frequent renter points(累加常客积点)
frequentRenterPoints ++;
if((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) &&
each.getDaysRented() > 1)
frequentRenterPoints ++;
result += "\t" + each.getMovie().getTitle() + "\t" +
String.valueOf(thisAmount) + "\n";
totalAmount += thisAmount;
}
// add footer lines(结尾打印)
result += "Amount owed is " + String.valueOf(totalAmount) + " \n";
result += "You earned " + String.valueOf(frequentRenterPoints) +
"frequent renter points";
return result;
}
下一件引我注意的事时:thisAmount如今变成多余了.它接受each.getCharge()的执行结果,然后就不再有任何改变.所以我可以运用Replace Temp with Query(120)把thisAmount除去:
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;
}
我喜欢尽量除去这一类临时变量.临时变量往往形成问题.它们会导致大量参数被传来传
去,而其实完全没有这种必要.你很容易失去它们的踪迹,尤其在长长的函数之中更是如此.当然我这么做也需付出性能上的代价,例如本例的费用就被计算了两
次.但是这很容易在Rental class中被优化.而且如果代码有合理的组织和管理,优化会有很好的效果.