重构 java 中的 if 语句

Refactoring if statement in java

我需要一些帮助来重构这个 if 语句。我想将百分比声明为常量。我还想制作一个方法,将代码包含在 if 括号内。我还可以做些什么?

if(totalReceiptsAmount >= getIncome() && totalReceiptsAmount <  0.20 * getIncome())
        setTaxIncrease(getBasicTax() + 0.05 * getBasicTax());
    if(totalReceiptsAmount >=  0.20 * getIncome() && totalReceiptsAmount <  0.40 * getIncome())
        setTaxIncrease(getBasicTax() - 0.05 * getBasicTax());
    if(totalReceiptsAmount >=  0.40 * getIncome() && totalReceiptsAmount <  0.60 * getIncome())
        setTaxIncrease(getBasicTax() - 0.10 * getBasicTax());
    if(totalReceiptsAmount >=  0.60 * getIncome())
        setTaxIncrease(getBasicTax() - 0.15 * getBasicTax());

您代码中的主要问题可能是代码重复,这意味着如果您想更改条件,您可能必须应用相同的更改所有四个条件。所以你可以尝试分解出共同的功能,正如你已经为条件所建议的那样。所以你可以定义一个方法

private boolean receiptsAmountIsBetweenFactorOfXAndYOfIncome(double x, double y){
    return totalReceiptsAmount >= x * getIncome() && totalReceiptsAmount < y  * getIncome();
}

并相应地更新您的 if 语句:

if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0, 0.2))
    setTaxIncrease(getBasicTax() + 0.05 * getBasicTax());
if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0.2, 0.4))
    setTaxIncrease(getBasicTax() - 0.05 * getBasicTax());
if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0.4, 0.6))
    setTaxIncrease(getBasicTax() - 0.10 * getBasicTax());
if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0.6, 1))
    setTaxIncrease(getBasicTax() - 0.15 * getBasicTax());

现在,if 语句的主体中仍然存在重复。所以你可以介绍另一种方法:

private void increaseTaxByFactorOfX(double x){
    setTaxIncrease(getBasicTax() + x * getBasicTax());
}

并再次更新 if 语句:

if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0, 0.2))
    increaseTaxByFactorOfX(0.05);
if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0.2, 0.4))
    increaseTaxByFactorOfX(-0.05);
if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0.4, 0.6))
    increaseTaxByFactorOfX(-0.10);
if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(0.6, 1))
    increaseTaxByFactorOfX(-0.15);

现在,如果需要,您可以检测所用数字中的模式,或者简单地将数字硬编码到数组或列表中,并使用循环而不是多个类似的 if 语句:

double[] factorOfIncome = {0, 0.2, 0.4, 0.6, 1};
double[] taxIncreaseFactor = {0.05, -0.05, -0.10, -0.15};

for(int i = 0; i<taxIncreaseFactor.length; i++)
    if(receiptsAmountIsBetweenFactorOfXAndYOfIncome(factorOfIncome[i], factorOfIncome[i+1]))
        increaseTaxByFactorOfX(taxIncreaseFactor[i]);

最后的重构步骤完全消除了重复,但在我看来,这会使代码更难理解。

编辑: 请注意,我假设第一个条件应该是

if(totalReceiptsAmount >= 0 * getIncome() && //... 

因为看起来这确实是您打算写的内容。如果不是这种情况,则需要单独处理第一个条件。