Stage 1: Problem
The Problem
You are building a pricing engine for a SaaS platform. Customers can be on different plans, and each plan has different discount rules:
typescript
| 1 | class InvoiceService { |
| 2 | calculateTotal(items: LineItem[], plan: string): number { |
| 3 | let subtotal = items.reduce((sum, i) => sum + i.price * i.quantity, 0); |
| 4 | |
| 5 | if (plan === "basic") { |
| 6 | // No discount |
| 7 | } else if (plan === "pro") { |
| 8 | subtotal *= 0.9; // 10% off |
| 9 | } else if (plan === "enterprise") { |
| 10 | if (subtotal > 10000) subtotal *= 0.75; // 25% off for large orders |
| 11 | else subtotal *= 0.85; // 15% off otherwise |
| 12 | } |
| 13 | |
| 14 | return subtotal; |
| 15 | } |
| 16 | } |
Now the business wants:
- Seasonal discounts ā Black Friday: flat 30% off, stacks with plan discounts.
- Loyalty discounts ā if the customer has been active for 2+ years, extra 5%.
- Coupon codes ā arbitrary discount logic defined by marketing.
- A/B testing ā try different discount strategies on different cohorts.
- Custom enterprise contracts ā each enterprise client negotiates their own pricing formula.
The if/else chain is about to explode. Each new rule interacts differently with existing ones. Testing any single strategy means setting up the entire InvoiceService.
How would you decouple the discount logic so each rule can vary independently?