| | | | | | | [文章信息] | | | 作者: | 张昱 | | 时间: | 2005-05-10 | | 出处: | blogchina | | 责任编辑: | 方舟 | |
| [文章导读] | | | 本文的目的是探索Eclipse自动重构可以在多大程度上辅助重构这个过程 | |
| |
|
| | | |
|
|
|
|
|
三、重构第二步:搬移"金额计算"代码
目的:
1、 将函数amountFor()转移到Rental类中,并更名为getCharge()。
2、 更新并替换所有对amountFor()的引用。
重构方法:
Move Method Change Method signatrue Inline Method Inline Temp
方法:
1、选中函数amountFor()的定义,在右键菜单中选择"重构/移动",显示参数设置对话框。把新方法名改成getCharge。按下"确定"按钮,Customer Class中的amountFor()函数被移动到Rental Class中,并更名为:getCharge()。
同时eclipse自动在Customer的amountFor()函数中添加一行对新函数的"委托"代码:
private double amountFor(Rental aRental) { return aRental.getCharge(); } | 这行代码会产生编译错误,原因是amountFor()的private型被传递到了新的方法中:
/** * @param this * @return */ private double getCharge() { …… } | 2、继续重构!选中getCharge()方法,在右键菜单中选择"重构/更改方法特征符",弹出参数选择对话框,把访问修饰符从private改成public。Eclipse的编译错误提示自动消失。
3、回到Customer类,把所有对amountFor()引用的地方替换成直接对getCharge()的引用。选中Customer类的函数amountFor(Rental aRental),在右键菜单中选择"重构/内联",出现参数选择对话框。
选择"确认"按钮,引用amountFor()的地方被替换成对getCharge()的引用。
public String statement() { …… double thisAmount = each.getCharge(); …… } | 4、除去临时变量thisAmount。
选中变量thisAmount,在右键菜单中选择"重构/内联",重构预览窗口如下,可见达到了重构的目的。按下"确认"按钮重构代码。
statement()代码:
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 ++; // 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(显示此笔租借数据) 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; } |
|
|
|
|
|
|
|
|