オブジェクト指向プログラミングを行っていて、クラスを持たない名詞を一貫して参照している場合、オブジェクト指向プログラミングを正しく行っていません。
public interface Tax {
public double taxOn(double value);
}
/**
* This class returns tax by table lookup, much like the first 100K in an USA IRS 1040.
*/
public class TableTax {
}
/**
* This class returns tax by formula, much like the tax for those making +$100K in a
* USA IRS 1040.
*/
public class CalculatedTax {
}
あなたのプログラムには少なくとも 6 つの税率が含まれていると思いますが、プログラムを更新する必要がある場合は、すべてのロジックを書き直す必要があります。優れたオブジェクト指向プログラミングは、明らかに置き換えられるものを置き換えるように設計されており、通常はインターフェイスを介して置き換え可能なコンポーネントを呼び出すことによって行われます。
次に、入力を受け取って「Tax」を返す「TaxFactory」を作成できます。
public TaxFactory {
public Tax getTaxFor(double value) {
tax = // however you decide which tax to use.
return tax;
}
}
今、あなたのコードは本当にきれいに見えます
double taxAmount = new TaxFactory().getTaxFor(earnings).taxOn(earnings);
--- 配列と for ループを使用する必要に応じて編集 ---
では、最初の 20,000 に 10%、次の 20,000 に 15%、次の 40,000 に 17%、それ以上に 20% の税金がかかるとしましょう。
double balance = taxable_amount;
double tax_bracket[][] = {{0.10, 20000}, {0.15, 20000}, {0.17, 40000}, {0.20, Double.MAX_VALUE}};
double tax = 0;
for (int index = 0; index < tax_bracket.length; index++) {
if (balance > 0) {
if (tax_bracket[index][1] < balance) {
// calculate fraction of tax for the entire bracket
tax += tax_bracket[index][0] * tax_bracket[index][1];
// deduct the taxed part of the balance
balance -= tax_bracket[index][1];
} else {
// calculate fraction of tax for the remaining balance
tax += tax_bracket[index][0] * balance;
// the entire balance has been taxed
balance = 0;
}
}
}
return tax;