I have a small webshop-like web application, and i have big plans 🙂
I have a basket object and a basketitem object, the basket has a list of basketitems. At runtime i dont have the list, it has to be loaded from database (using a repository pattern) with the id of the basket. The basket can exist for several days (max 30 days) and the customer can add basketItems to the basket during this interval.
What is the best approach to calculating the total (i have several similar calculations to make) of the basket, should i maintain a field in the database and update it when i add something to the basket or should i calculate it on the fly as a property (for databinding purposes)?
Lets say I have to make two calculations on this basket, one for the total, and one with a discount (tricky algorithm, dependent on many variables).
How about 3, 4 or 5 calculations, which is the best approach?
I would calculate the total on the fly – if the price of any of the individual items change whilst they are in a customer basket, then I would imagine that you would want to sell them at the new price if the prices have gone up or would want to pass any savings on to the customer if they have gone down 🙂
If you’re storing it in a database, it’s redundant data – you have all of the data that you need to calculate it already stored against the individual items. It also means that you would need to update that database table/field each time the user logs in to update the total.