如果你在做面向对象的编程,并且你一直引用一个你没有类的名词,那么你就没有做面向对象的编程。
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 {
}
我在你的程序中至少计算了六个税率,如果你需要更新它,你将不得不重写所有的逻辑。良好的面向对象编程旨在替换显然将要替换的内容,通常通过接口调用可替换组件。
然后你可以制作“TaxFactory”,它接受一个输入并返回一个“Tax”。
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;