本文用eclipse的自動重構(gòu)功能對一個程序?qū)嵗M行重構(gòu),目的是探索Eclipse自動重構(gòu)可以在多大程度上輔助重構(gòu)這個過程。程序?qū)嵗褂谩禦efactoring:Improving the Design of Existing Code》一書中的例子。
本文使用《Refactoring:Improving the Design of Existing Code》一書第一章的例子。重構(gòu)前的代碼及每一步重構(gòu)后的代碼見附件。讀者最好配合《Refactoring:Improving the Design of Existing Code》一書閱讀本文。
public String statement() { double totalAmount = 0; // 總消費金額 int frequentRenterPoints = 0; // 常客積點 Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + getName() + " ";
while(rentals.hasMoreElements()){ Rental each = (Rental)rentals.nextElement(); //取得一筆租借記錄
// add frequent renter points(累加 ??头e點) frequentRenterPoints ++; // add bouns for a two day new release rental if((each.getMovie().getPriceCode())==Movie.NEW_RELEASE each.getDaysRented()>1) frequentRenterPoints ++;
// show figures for this rental(顯示此筆租借數(shù)據(jù)) result += " " + each.getMovie().getTitle() + " " + String.valueOf(each.getCharge()) + " "; totalAmount += each.getCharge(); }
// add footer lines(結(jié)尾打?。? result += "Amount owed is " + String.valueOf(totalAmount) + " "; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points";
return result; }
四、重構(gòu)第三步:提煉"??头e點計算"代碼
目的:提取"??头e點計算"代碼并放在Rental類中,"常客積點計算"代碼如下。
public String statement() { …… // add frequent renter points frequentRenterPoints ++; // add bouns for a two day new release rental if((each.getMovie().getPriceCode())==Movie.NEW_RELEASE each.getDaysRented()>1) frequentRenterPoints ++; …… }
class Movie …… /** * @param this * @return */ public double getCharge(int _daysRented) { double result = 0; switch(getPriceCode()){ //取得影片出租價格 case Movie.REGULAR: // 普通片 result += 2; if(_daysRented>2) result += (_daysRented-2)*1.5; break;
case Movie.NEW_RELEASE: // 新片 result += _daysRented*3; break;
case Movie.CHILDRENS: // 兒童片 result += 1.5; if(_daysRented>3) result += (_daysRented-3)*1.5; break; } return result; }
class Rental…… /** * @param this * @return */ public double getCharge() { return _movie.getCharge(_daysRented); }
2、用同樣的步驟處理getFrequentRenterPoints(),重構(gòu)后的代碼:
class Movie …… /** * @param frequentRenterPoints * @param this * @return */ public int getFrequentRenterPoints(int daysRented) { if((getPriceCode())==Movie.NEW_RELEASE daysRented>1) return 2; else return 1; } class Rental…… /** * @param frequentRenterPoints * @param this * @return */ public int getFrequentRenterPoints(int daysRented) { if((getPriceCode())==Movie.NEW_RELEASE daysRented>1) return 2; else return 1; }