如何将功能重构为目标功能?

时间:2019-09-13 17:06:41

标签: java math refactoring

Bob叔叔在他的“干净代码”中提供了没有步骤的重构示例,因此我试图在阅读时复制它们。

原始代码:

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会这样?

1 个答案:

答案 0 :(得分:0)

0.5 * tenthRate来自加班率(1.5 * tenthRate)和非加班率(1.0 * tenthRate)之间的差异。

重构版本背后的逻辑是,您无需为非加班和加班时间计算单独的工资额,而只需为整个小时数支付标准费率 strong>,然后为加班者加分。