原始代碼核心問題
- 語法錯誤:類定義缺少
class SalaryStandard { 起始大括號,導致無法編譯;
- 方法簽名錯誤:
OPay、PaymentRules、Commission 等私有方法缺少返回類型聲明(應為 double);
- 邏輯漏洞:
PaymentRules 中 NoOfDay >= 60 條件缺失 45-59 區間,導致該範圍天數無獎勵/懲罰;
- 行政薪資計算缺少
break:AdminiSalary 的 switch 缺少 break,會發生「貫穿」導致所有級別薪資相同;
- 字段命名不規範:駝峰與下劃線混用,建議統一
camelCase;
- 硬編碼常量:基礎工資、比例直接寫死,應提取為
static final 常量或配置文件。
重構後的核心類結構
public class SalaryStandard {
// 常量提取
private static final double MANAGER_BASE_1 = 9000 * 12;
private static final double PROFIT_RATIO = 0.04 / 3;
// ... 其他常量
// 字段
private double managedPayroll;
private double salesWage;
private double technicalSalary;
private double executivePay;
private double cashReward;
private double businessProfitRoyalty;
private double overtimePay;
// 私有輔助方法:加班費
private double calculateOvertimePay(int days, int level) {
if (days == 0) return 0;
double rate = (level == 1) ? 150 : (level == 2 ? 100 : 50);
return days * rate;
}
// 私有輔助方法:回款獎勵
private double calculateCashReward(int days, double profit) {
if (days < 30) return 0.005 * profit;
if (days < 45) return 0.002 * profit;
if (days < 60) return 0; // 修正:補全 45-59 區間
return -0.002 * profit;
}
// 私有輔助方法:利潤提成
private double calculateCommission(double profit) {
if (profit <= 1_000_000) return 0.02 * profit;
if (profit <= 5_000_000) return 0.035 * profit;
return 0.055 * profit;
}
// 公開業務方法示例
public double calculateManagerSalary(int level, double grossProfit, int managerCount) {
double base = (level == 1) ? MANAGER_BASE_1 : (level == 2 ? 8000 * 12 : 7000 * 12);
return base + grossProfit * PROFIT_RATIO / managerCount;
}
public double calculateSalesSalary(int level, int cashDays, double profit) {
double base = (level == 1) ? 3000 : (level == 2 ? 2200 : 2000);
return base + calculateCashReward(cashDays, profit) + calculateCommission(profit);
}
public double calculateTechnicalSalary(int level, int overtimeDays) {
double base = (level == 1) ? 15000 : (level == 2 ? 10000 : 5000);
return base + calculateOvertimePay(overtimeDays, level);
}
public double calculateAdminSalary(int level) {
switch (level) {
case 1: return 2300;
case 2: return 2000;
case 3: return 2000 * 0.8;
default: throw new IllegalArgumentException("未知行政級別");
}
}
}
代碼質量提升清單
- 編譯通過:修復所有語法錯誤;
- 單元測試覆蓋:針對各級別、邊界值(0 天、負利潤等)編寫 JUnit 測試;
- 策略模式擴展:若薪資規則頻繁變動,可將各計算邏輯抽取為
SalaryStrategy 接口實現類,運行時注入;
- 配置外部化:基礎工資、比例放入 YAML/Properties,支援熱更新;
- 文檔註釋:為公共方法補全 Javadoc,說明參數含義與業務規則。