A cart operation is a function that knows the structural representation of a shopping cart, such as an array containing item objects. It differs from a business rule: carts are broadly reusable across stores, while rules such as free shipping belong to a particular business. section 5.11
Recognize cart operations by the work they perform:
- Add, remove, find, count, or update items in the cart. section 6.1
- Keep cart structure separate from item operations and business rules as layers become clearer. section 5.6
- Treat a function that mixes cart structure with business rules as a possible design smell. section 5.11
C I function add_item(cart, name, price) { var new_cart = cart.slice(); #1 new_cart.push({ name: name, price: price }); return new_cart; }
C I B function calc_total(cart) { #2 var total = 0; for(var i = 0; i < cart.length; i++) { var item = cart[i]; total += item.price; } return total; }
B function gets_free_shipping(cart) { return calc_total(cart) >= 20; }
B function calc_tax(amount) { return amount * 0.10; }
Use the annotated listing to compare an add-item cart operation with calculations that also involve item structure or business rules. section 5.6
