ivaneeo's blog

自由的力量,自由的生活。

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  669 Posts :: 0 Stories :: 64 Comments :: 0 Trackbacks
正如我在前面提过的,临时变量可能是个问题。它们只在自己所属的函数中有效,所以它们会助长[冗长而复杂]的函数。这里我们有两个临时变量,两者都是用来 从Customer对象相关的Rental对象中获得某个总量。不论ASCII版或HTML版都需要这些总量。我打算运用Replace Temp with Query(120),并利用所谓的query method来取代totalAmount或frequentRentalPoints这两个临时变量。由于class内的任何函数都可以取用(调用)上述所谓query methods,所以它可能够促进较干净的设计,而非冗长复杂的函数:

class Customer...
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;
}

首先我以Customer class的getTotalCharge()取代totalAmount:
class Customer...
public String statement() {
    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";
    }
//   add footer lines(结尾打印)
    result += "Amount owed is " + String.valueOf(getTotalCharge()) + " \n";
    result += "You earned " + String.valueOf(frequentRenterPoints) +
       "frequent renter points";
    return result;
}

//  译注:次即query method
private double getTotalCharge() {
    double result = 0;
    Enumeration rentals = _rentals.elements();
    while(rentals.hasMoreElements()) {
       Rental each = (Rental)rentals.nextElement();
       result += each.getCharge();
    }
    return result;
}
这并不是Replace Temp with Query(120)的最简单情况。由于totalAmount在循环内部被赋值,我不得不把循环复制到query method中
posted on 2005-08-15 13:55 ivaneeo 阅读(138) 评论(0)  编辑  收藏 所属分类: refactoring-从地狱中重生

只有注册用户登录后才能发表评论。


网站导航: