鲍勃叔叔在他的“干净代码”中提供了无需步骤的重构示例,因此我在阅读时尝试复制它们。
原始代码:
public int calculateWeeklyPay(boolean overtime) {
int tenthRate = getTenthRate();
int tenthsWorked = getTenthsWorked();
int straightTime = Math.min(400, tenthsWorked);
int overTime = Math.max(0, tenthsWorked - straightTime);
int straightPay = straightTime * tenthRate;
double overtimeRate = overtime ? 1.5 : 1.0 * tenthRate;
int overtimePay = (int)Math.round(overTime*overtimeRate);
return straightPay + overtimePay;
}
重构:
public int straightPay() {
return getTenthsWorked() * getTenthRate();
}
public int overTimePay() {
int overTimeTenths = Math.max(0, getTenthsWorked() - 400);
int overTimePay = overTimeBonus(overTimeTenths);
return straightPay() + overTimePay;
}
private int overTimeBonus(int overTimeTenths) {
double bonus = 0.5 * getTenthRate() * overTimeTenths;
return (int) Math.round(bonus);
}
问题出在加类费上。当我尝试替换变量和函数时,我得到以下结果:
overtimePay = round(max(0, tenthsWorked - min(400, tenthsWorked))*tenthRate);
在原始和目标中
overtimePay = round(0.5 * tenthRate * max(0, tenthsWorked - 400));
为什么是 0.5?
另外,原来的overtimeRate
中可能少了一个“)”,但是不管怎样,为什么新的overtimePay
是这样的呢?
最佳答案
0.5 * tenthRate
来自加类率 ( 1.5 * tenthRate
) 和非加类率 ( 1.0 * tenthRate
) 之间的差异。
重构版本背后的逻辑是,您不必为非加类时间和加类时间单独计算工资金额,而只需为整个工作时间支付标准费率然后给加类加点奖金。
关于java - 如何将函数重构为目标函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57927734/