Skip to main content

Swappable Discount Policy

Challenge on lesson: Checkpoint: Design with Contracts

Design a discount engine behind a contract: - sealed interface Discount permits None, Percent, Flat inside Solution - record None(), record Percent(int pct), record Flat(int cents) - static int apply(Discount d, int priceCents) dispatching with a pattern switch: - None → price unchanged - Percent(pct) → price - price*pct/100 (integer division) - Flat(cents) → price - cents, but never below 0 - static Discount best(List<Discount> options, int priceCents) returning the policy that yields the LOWEST final price. Fail fast: Percent outside 0..100 throws IllegalArgumentException.

Difficulty: intermediate

Back to lesson: Checkpoint: Design with Contracts