Logic Errors :: 0x31
You're reviewing a pull request from another developer who is building a replacement online store for your company.
You look through the diff quickly and see that the feature they're currently working on is to add discounts to a shopping cart object.
@@ -2,7 +2,8 @@ class Cart
SALES_TAX = 0.05
def initialize
- @items = []
+ @items = []
+ @discount = 0
end
def <<(item)
@@ -13,10 +14,14 @@ class Cart
@items.sum(&:price)
end
+ def apply_discount(amount)
+ @discount = amount
+ end
+
def total
tax_adjustment = (1 + SALES_TAX)
- (subtotal * tax_adjustment).round(2)
+ ((subtotal * tax_adjustment) - @discount).round(2)
end
end
@@ -26,6 +31,8 @@ cart = Cart.new
cart << LineItem["An exciting shirt", 21]
cart << LineItem["An equally exciting pair of socks", 5]
-if cart.total != 27.30
+cart.apply_discount(5.00)
+
+if cart.total != 22.30
fail "Something went wrong! Please check your calculations."
end
You notice there is a test at the bottom of the diff which has been modified to reflect the new feature in use, but something about it looks off to you.
So you investigate a little further, just to be sure.
You pull up the old online store app and create two products with the same names and prices shown in the test, and then add them to the cart. And then you create a $5 off coupon and apply it in the cart.
After doing that, you see that the total listed in the old app is $22.05 and not $22.30 as the test code in this new change indicated. The old app has been online for a decade, and you can safely assume that its math is correct.
(1) What did the developer of the new app get wrong about the logic for how discounts should be applied?
(2) Suppose that instead of the values used in this example, you had two items, one costing $75 and the other costing $25, the sales tax was 10%, and the discount was $10. What would be the correct total then?
You can preorder now to be among the first to gain access when it is released.