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);
現在,如果你願意,你可以在使用numericals檢測模式,或只需硬編碼數組或列表中的數字,並使用循環代替多個類似的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]);
This la st重構步驟完全擺脫了重複,但在我看來使代碼有點不太可以理解。
編輯:注意,我認爲第一個條件應該是
if(totalReceiptsAmount >= 0 * getIncome() && //...
,因爲它確實看起來這是你打算寫什麼。如果情況並非如此,那麼第一個條件將需要分開處理。
使用'else if's去除重複檢查並分解函數調用,只存儲ifs中的百分比。 – miniBill
嗯,我起初是這麼做的,但是我們的教授告訴我們只用'if if'來重構'else if' – flower
這種感覺不對......任何理由呢? – miniBill