Design patterns · core
Strategy pattern for changing rules
Strategy puts each rule in its own class behind one interface, so the code that uses the rule does not change. It is the answer to fare rules, pricing, allocation order and rate limit algorithms.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- A FareRule interface with apply(current fare, trip context), one class per rule. A FareCalculator runs an ordered list of rules. A new rule is a new class plus one config entry.
- Make the order and stacking explicit: base fare, per-km, surge multiplier, fixed fees, discounts, rounding. It must not depend on where the code happens to sit.
- Keep numbers (multipliers, fees) in config or a rules table per city, with versions, so tuning needs no deploy. Code is only for new kinds of rule.
- Choose the rules per city and ride type by a factory or config.
- Test each rule alone, and add golden tests for full fares.
- Store the fare breakdown and rule versions on each trip so a wrong fare can be traced and refunded.
- Money in paise or BigDecimal, and round once at the end.
- Strategy appears in many problems: SlotAllocationStrategy in a parking lot, EvictionPolicy in a cache, matching and pricing in cab booking.
The red pen
Common traps: mistake → fix
Mistake: Replacing if/else with a switch is Strategy
Fix: a switch still changes for every new rule.
Mistake: One Strategy class per city with copied code is good
Fix: shared code gets copied and drifts; use data for the numbers.
Mistake: Magic numbers in code are fine for fares
Fix: they need a deploy to change and have no history.
Easy to hard
Questions interviewers ask, easy to hard
- What is the Strategy pattern? Give a real example.
- Fare rules change every month. How do you design it?
- How do you keep the order of rules clear?
- How do you trace a wrong fare back to its rules?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.