Skip to main content

Practice · 1 of 4

Strategy: Kill the Shipping Switch

CHALLENGE
Difficulty: intermediate+25 XP

LegacyCheckout.Cost prices shipping by a mode string, and every new carrier means another else if. Replace the switch with **Strategy**: 1. IShippingCost { decimal Cost(Solution.Parcel p); } (inside Solution) 2. Two implementations: Flat (always 3.5m) and Weight (0.8m per kg, minimum 4m) 3. Solution.Cost(Parcel p, IShippingCost strategy) delegates entirely — zero conditionals on weight/mode in Solution.Cost itself. The value is *composition by the caller*: the tests pass strategies by hand, proving the context depends only on the abstraction. ``csharp public static class Solution { public sealed class Parcel { public decimal WeightKg; } public interface IShippingCost { decimal Cost(Parcel p); } public static decimal Cost(Parcel p, IShippingCost strategy); } ``

Back to lesson: Practice: Patterns Practice: Strategy, Decorator, Builder