Skip to main content

Swappable Discount Policy

Challenge on lesson: Checkpoint: Design with Contracts

CHALLENGE
Difficulty: intermediate+25 XP

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.

Back to lesson: Checkpoint: Design with Contracts