如何将函数重构为目标函数?



在他的"干净代码"中,鲍勃叔叔有没有步骤的重构的例子,所以我在阅读时尝试复制它们。

原始代码:

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(之间的差异。

重构版本背后的逻辑是,与其为非加班和加班时间单独计算工资,不如只支付整套小时的标准费率,然后为加班加班加奖金。

最新更新