Skip to main content

Sign in to CleanKata

Track your progress, earn XP, and unlock every lesson.

By signing in you agree to our Terms of Use and Privacy Policy.

Design Patterns80 XP8 min

Strategy: Algorithm Swapping

Define a family of algorithms, encapsulate each in its own class, and make them interchangeable at runtime — eliminate conditionals by selecting behavior through composition.

Why this matters

A checkout that handles PayPal, card, and bank transfer with a long if/elif block violates the Open-Closed Principle: adding crypto requires editing the checkout class. Strategy encapsulates each algorithm in its own class and injects it at the call site. The checkout delegates to whatever strategy it receives — adding crypto means writing a new class and wiring it in, zero edits to existing code.

Strategy vs. State

Strategy and State look structurally identical — both inject a polymorphic object that the context delegates to. The difference is intent: a Strategy is selected by the client and usually doesn't change after construction; a State transitions itself internally as the object moves through its lifecycle. When in doubt: if the algorithm is chosen externally, it's a Strategy; if the object changes its own behavior over time, it's a State.

💡Key takeaway

Every if/elif on a "type" field that selects an algorithm is a Strategy waiting to be extracted — encapsulate each variant, inject it, and new variants add code rather than modifying it.

🔧 Some exercises may still have errors. If something seems wrong, use the Feedback button (bottom-right of the page) to report it — it helps us fix it fast.

Hint: Every if/elif on a 'type' field that selects an algorithm is a Strategy pattern waiting to be extracted.

✗ Your version