Discount Logic That Gives Money Away
An online shop applies discounts with this rule set: orders of 100 or more get 10% off; orders of 200 or more get 20% off; orders of 500 or more get 30% off. The programmer writes three separate if statements (not else if), each subtracting its percentage from the running total. A customer places an order of 600 and is charged far less than expected. Separately, a customer places an order of exactly 200 and receives 20% off, but a colleague argues the 10% should also have applied because '200 is at least 100'. The programmer also forgot to handle negative totals after discounts.
1. Explain why the 600 order is charged incorrectly, and state whether the tiers should be cumulative or exclusive.
Read the worked answer
Because the three if statements are independent, all three conditions are true for a 600 order (600 >= 100, >= 200, >= 500). The program subtracts 10%, then 20% of the new total, then 30% of that total - compounding three discounts instead of applying one.
The tiers are meant to be exclusive: a customer qualifies for the single highest applicable discount, not the sum of all lower ones. The correct structure is an if / else-if chain ordered from highest threshold down (or lowest up with the first match winning), so exactly one branch executes.
So the 600 customer should receive 30% off only. Using independent ifs turned a selection problem into an accumulation problem.
2. Address the colleague's claim that an order of exactly 200 should also get the 10%.
Read the worked answer
The colleague is confusing 'qualifies for' with 'receives'. An order of 200 meets the 10% threshold, but under exclusive tiering it receives only the best single discount it qualifies for, which is 20%. Applying both would be cumulative discounting, which the pricing rule does not intend (and which the 600 case shows is financially wrong).
The key judgement: thresholds define eligibility, and a selection structure must pick exactly one outcome. If the business genuinely wanted stacking, the rule would have to say so explicitly and the order of application would need defining - it does not.
3. The programmer wants to prevent negative totals after discounting. Propose a robust approach and explain the trade-off.
Read the worked answer
Two reasonable approaches:
- Clamp the final total:
total = max(total, 0). Simple, guarantees no negative charge. - Validate inputs before discounting: reject or flag orders where the computed discount exceeds the total, treating it as a data error.
The trade-off: clamping silently hides a logic or data problem (a discount larger than the order suggests a bug or bad input), whereas validation surfaces it but requires handling an error path. For money-handling code, validation is usually preferable because a silent clamp can mask a serious defect. A combined approach - validate, and clamp as a last-resort safety net with logging - gives both safety and visibility.