我正在阅读干净的代码,在第 17 节中,据说当一个类对另一个类的字段和函数更感兴趣时,这意味着特征嫉妒。那么那里存在以下示例:
public class HourlyPayCalculator {
public Money calculateWeeklyPay(HourlyEmployee e) {
int tenthRate = e.getTenthRate().getPennies();
int tenthsWorked = e.getTenthsWorked();
int straightTime = Math.min(400, tenthsWorked);
int overTime = Math.max(0, tenthsWorked - straightTime);
int straightPay = straightTime * tenthRate;
int overtimePay = (int)Math.round(overTime*tenthRate*1.5);
return new Money(straightPay + overtimePay);
}
}
这个样本的功能如何令人羡慕?
谁能帮我解释一下吗?
提前谢谢您。
在您的示例中,calculateWeeklyPay显示出功能嫉妒的迹象,因为它严重依赖于HourlyEmployee类的内部。 HourlyEmployee 类可以有一个类似 calculatePay 的方法在内部执行这些计算,而不是向 HourlyEmployee 询问其字段,然后在其外部计算工资。
可以这样重构:
public class HourlyEmployee {
// ... Other methods and fields ...
public Money calculateWeeklyPay() {
int tenthRate = this.getTenthRate().getPennies();
int tenthsWorked = this.getTenthsWorked();
int straightTime = Math.min(400, tenthsWorked);
int overTime = Math.max(0, tenthsWorked - straightTime);
int straightPay = straightTime * tenthRate;
int overtimePay = (int)Math.round(overTime*tenthRate*1.5);
return new Money(straightPay + overtimePay);
}
}
// And then the HourlyPayCalculator would be simplified:
public class HourlyPayCalculator {
public Money calculateWeeklyPay(HourlyEmployee e) {
return e.calculateWeeklyPay();
}
}