Refactor a Tangled Checkout Discount Calculator Into Strategies
Last updated: November 29, 2026
Quick Overview
You are given a checkout function with a long chain of if/else branches for buy-two-get-one-free, category percentage discounts and spend thresholds. Refactor it, with tests guarding behaviour, into a design where new promotion types can be added without editing the checkout code.
Thoughtworks
November 29, 20260
0
0 solved
You are given a checkout function with a long chain of if/else branches for buy-two-get-one-free, category percentage discounts and spend thresholds. Refactor it, with tests guarding behaviour, into a design where new promotion types can be added without editing the checkout code.
This mirrors the pairing session in a Thoughtworks loop, where an interviewer sits with you on a small codebase for a retail client and asks you to extend or clean it up. They watch whether you write a safety net of tests first, take small refactoring steps, and talk through design choices like a consultant would with a client developer.
What the Interviewer Expects
- Writes or confirms tests that pin current totals before changing structure
- Extracts a DiscountRule abstraction with one class per promotion
- Keeps Checkout closed to modification when a new rule is added
- Uses small, named refactoring steps and keeps the build green
- Discusses rule interaction (stacking, ordering, caps) with the interviewer
- Avoids floating point surprises in money, or at least names the risk
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- The business now says only the single best discount should apply. What changes?
- How would you load rules from configuration managed by the client's merchandising team?
- Where would you switch from float to Decimal or integer cents, and how do you migrate safely?
- How do you explain this refactor's value to a client product owner who sees no new features?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
Three promotion types exist: buy X get Y free on a SKU, a percentage off a category, and a fixed amount off once the basket passes a threshold. Today all discounts stack. The total must never go below...
High-Level Design
Step 1: characterization tests for a handful of baskets (empty, only promo items, mixed, threshold edge). Step 2: extract each branch into a method, then into a class implementing `DiscountRule.discou...