Quick Index
Code Explanation


Greetings, my name is TaxCalculator.

I am a simple calculator that calculates the tax for a Taxable type.

Note that my element must be a Taxable object type. I do not care if my ivar "element" is a car, house, etc. As long as it's a Taxable type, I'm happy.

I use OO encapsulation. I hide the unpleasant details of money math (rounding errors).

Read more about me below.

element -- the taxable element
taxRate -- the applicable tax rate (as decimal).
salesTax, afterTaxPrice -- output values
public class TaxCalculator {
	private Taxable element;
	private BigDecimal taxRate, salesTax, afterTaxPrice;
	private static DecimalFormat formatter = new DecimalFormat("0.00");

	//etc (more code follows)

}
tax rate is decimal
User-friendly string param
	public TaxCalculator(Taxable aElement, String aTaxRate)  {
		this.element = aElement;
		this.taxRate = new BigDecimal(aTaxRate);
	}
Do the calc!
Calc tax and afterTaxPrice
	public void calculate()  {
		BigDecimal taxFactor, before, tax, after;
		taxFactor = getTaxRate();
		before = getElement().beforeTaxPrice();
		tax = before.multiply(taxFactor);
		after = before.add(tax);
		this.salesTax = tax;
		this.afterTaxPrice = after;
	}

Complete Source Code


Here is all my code.

Happy coding.

Thank you,
TaxCalculator
package taxcalc.model;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class TaxCalculator {

	private Taxable element;
	private BigDecimal
		taxRate,
		salesTax,
		afterTaxPrice;
	
	private static DecimalFormat formatter = new DecimalFormat("0.00");

	public TaxCalculator(Taxable aElement, String aTaxRate) {
		this.element = aElement;
		this.taxRate = new BigDecimal(aTaxRate);
	}
	
	public Taxable getElement() {
		return element;
	}

	public BigDecimal getTaxRate() {
		return taxRate;
	}
	
	public BigDecimal getSalesTax() {
		return salesTax;
	}

	public BigDecimal getAfterTaxPrice() {
		return afterTaxPrice;
	}
	
	public String getSalesTaxFormatted() {
		return formatter.format(this.getSalesTax());
	}

	public String getAfterTaxPriceFormatted() {
		return formatter.format(this.getAfterTaxPrice());
	}

	public void calculate() {
		BigDecimal taxFactor, before, tax, after;
		taxFactor = getTaxRate();
		before = getElement().beforeTaxPrice();
		tax = before.multiply(taxFactor);
		after = before.add(tax);
		this.salesTax = tax;
		this.afterTaxPrice = after;
	}
	
	@Override
	public String toString() {
		return "Taxable Element -- " + getElement().toString();
	}

}