【发布时间】:2016-09-06 20:56:38
【问题描述】:
我正在寻找重构太长的方法。搜索我发现了这个技术:Replace Method with Method Object 但我完全不明白。
如果要重构的方法是:
public class Order {
//Method to refactor
public double price() {
double primaryBasePrice;
double secondaryBasePrice;
double tertiaryBasePrice;
//compute impl
}
//.....
}
对于 web 示例,重构 Replace Method with Method Object 将如下所示:
public class Order {
//Method refactored
public double price() {
return new PriceCalculator(this).compute();
}
//.......
}
//Method object
public class PriceCalculator {
private double primaryBasePrice;
private double secondaryBasePrice;
private double tertiaryBasePrice;
public PriceCalculator(Order order) {
//??
}
public double compute() {
// impl
}
}
但是PriceCalculator 如何获取primaryBasePrice、secondaryBasePrice、tertiaryBasePrice 值来进行计算?
我只看到可以将构造函数中的值作为下一个传递:
//Method object
public class PriceCalculator {
private double primaryBasePrice;
private double secondaryBasePrice;
private double tertiaryBasePrice;
public PriceCalculator(Order order, double primaryBasePrice,
double secondaryBasePrice, double tertiaryBasePrice) {
this.primaryBasePrice = primaryBasePrice;
this.secondaryBasePrice = secondaryBasePrice;
this.tertiaryBasePrice = tertiaryBasePrice;
}
public double compute() {
// impl
}
}
否则,为什么要传入构造函数order实例引用?为什么需要?
-
传递
order的实例:return new PriceCalculator(this, primaryBasePrice, secondaryBasePrice, tertiaryBasePrice).compute(); -
没有
order实例引用:return new PriceCalculator(primaryBasePrice, secondaryBasePrice, tertiaryBasePrice).compute();
【问题讨论】:
标签: java c# coding-style refactoring