Posted on September 25, 2007 @ 02:07
I recently came across a problem, and I thought I would try to flex some of my developer muscle to try to solve it. The problem reads as follows:
To solve this problem I used a composite to calculate taxes.
The “TaxComposite” type allows you to bundle several different taxes all in one type.
So when calculating taxes, the calculation with iterate through all the taxes and add the calculated tax and return the total value.
"The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly." - Head First Design Patterns
I used a TaxFactory type to construct the TaxComposite type which gathers all the taxes that match a specified predicate and injects it into the TaxComposite constructor. It looks like…
The tax type is an enum that uses the flags attribute so that I can enable different bits for different taxes.
Taxes is a static type that contains different types of taxes. The FindBy method allows for different strategies to be passed into to gather different types of taxes based on different critera. The above example returns all the taxes that are enabled in the “forTaxes” argument. FindBy is defined like…
I’m not sure if this is the most flexible design, but if i need to make changes to tax rates I can do that in one spot.
The only catch is that it requires a re-compile to take a effect.
In a full blown implementation I may want to consider using a “service” to retrieve the tax rates.
Also, in this implementation in order to add new taxes I have to added it too 2 different locations.
The first is the TaxTypes enum and the second is the Taxes static holder class. This leaves a bit of a smell…