Defeating the if/else Monolith

By The Coding Gopher

Published: 2026-10-13

URL: https://thecodinggopher.substack.com/p/mastering-the-strategy-design-pattern


As applications grow, one of the most common anti-patterns developers encounter is the dreaded “God method”—a massive function bloated with endless if, elif, and switch statements attempting to handle every possible variation of a business rule.

The Strategy Pattern is a behavioral design pattern engineered specifically to solve this problem. It allows you to define a family of algorithms (or behaviors), encapsulate each one into its own separate class, and make them interchangeable at runtime.Strategy Design Pattern - HomeThe Strategy Design Pattern is a behavioral software design pattern that defines a family of algorithms, encapsulates each one in a separate class, and makes them interchangeable at runtime. This pattern allows an object's behavior to change dynamically without altering the class that uses it, directly supporting the Open/Closed Principle.

Instead of writing a single class that tries to do everything, the Strategy Pattern lets your code seamlessly swap out how a task is performed without altering the core system that relies on it.

Note: The Open-Closed Principle (OCP) is a core concept in software engineering. It states that software entities (classes, modules, and functions) should be open for extension, but closed for modification. This means you can add new features or behavior to your code without rewriting or editing existing source code.

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.

The Problem: The Exploding Conditional

Imagine you are building an e-commerce checkout system. Initially, you only support credit card payments. Your ShoppingCart class has a simple checkout() method.

A month later, the business wants to add PayPal. Then Apple Pay. Then Cryptocurrency. Suddenly, your checkout method looks like this:

class ShoppingCart:
def checkout(self, amount, payment_method):
if payment_method == "credit_card":
print("Processing credit card...")
# 50 lines of credit card logic
elif payment_method == "paypal":
print("Redirecting to PayPal...")
# 30 lines of PayPal logic
elif payment_method == "crypto":
print("Verifying blockchain transaction...")
# 40 lines of Crypto logic
else:
raise ValueError("Unsupported payment method")

Every time marketing adds a new payment method, you have to pry open the ShoppingCart class, modify its core logic, and risk breaking the entire checkout flow. This violates the Open/Closed Principle: software entities should be open for extension, but closed for modification.

Build Redis, Git, Docker & Claude Code From Scratch

Want to become a better software engineer?

Trusted by engineers at Google, NVIDIA, and Anthropic, CodeCrafters helps you rebuild technologies like Redis, Git, Docker, and Claude Code from scratch so you can deeply understand how real systems work.

We’ve partnered with CodeCrafters to give all readers an exclusive 40% lifetime discount.

💡 Engineers may expense platforms like this through their team’s learning budget.

Start Building & Unlock 40% Off

The Solution: Interchangeable Behaviors

The Strategy Pattern fixes this by pulling those individual payment algorithms out of the ShoppingCart and placing them into their own isolated classes.

The Anatomy of the Pattern

The Strategy Pattern consists of three main parts:

-

The Strategy Interface: A common interface that all specific strategies must implement.

-

Concrete Strategies: The individual classes that implement the interface (e.g., CreditCardStrategy, PayPalStrategy).

-

The Context: The class that utilizes the strategy (e.g., the ShoppingCart). It doesn’t know how the strategy works; it just knows how to trigger it.

StrategyThe Strategy Design Pattern is a behavioral programming pattern that defines a family of algorithms, puts each into a separate class, and makes their objects interchangeable. It lets the algorithm change independently from the clients that use it, allowing code behavior to adapt dynamically at runtime without massive conditional statements.

Refactoring to the Strategy Pattern

Let’s rewrite our e-commerce example in Python using this pattern:

from abc import ABC, abstractmethod

# 1. The Strategy Interface
class PaymentStrategy(ABC):
@abstractmethod
def pay(self, amount: float) -> None:
pass

# 2. Concrete Strategies
class CreditCardPayment(PaymentStrategy):
def pay(self, amount: float) -> None:
print(f"Charging ${amount:.2f} to Credit Card. Validating CVV...")

class PayPalPayment(PaymentStrategy):
def pay(self, amount: float) -> None:
print(f"Redirecting to PayPal to authorize ${amount:.2f}...")

class CryptoPayment(PaymentStrategy):
def pay(self, amount: float) -> None:
print(f"Generating wallet address for ${amount:.2f} equivalent in BTC...")

# 3. The Context
class ShoppingCart:
def __init__(self):
self.items = []
# The Context holds a reference to a Strategy object
self._payment_strategy = None

def set_payment_strategy(self, strategy: PaymentStrategy) -> None:
"""Allows changing the strategy dynamically at runtime."""
self._payment_strategy = strategy

def checkout(self, amount: float) -> None:
if not self._payment_strategy:
raise Exception("Please select a payment method before checking out.")

# The Context delegates the work to the attached strategy object
self._payment_strategy.pay(amount)

Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.

See It in Action

Now, the ShoppingCart is entirely decoupled from the payment logic.

cart = ShoppingCart()

# User selects PayPal
cart.set_payment_strategy(PayPalPayment())
cart.checkout(150.00)
# Output: Redirecting to PayPal to authorize $150.00...

# User changes mind, switches to Crypto
cart.set_payment_strategy(CryptoPayment())
cart.checkout(150.00)
# Output: Generating wallet address for $150.00 equivalent in BTC...

Enterprise Use Cases

Strategy Design Pattern will help you refactor code | TheCodeMan

The Strategy Pattern is ubiquitous in large-scale systems where flexibility is paramount:

-

Routing Algorithms: A navigation app calculating a route. The Context is the map; the Strategies are DriveRouteStrategy, WalkRouteStrategy, and TransitRouteStrategy.

-

Data Exporters: A reporting dashboard that lets users download data. The core report engine generates the raw data, but delegates to CSVExportStrategy, PDFExportStrategy, or JSONExportStrategy for the final formatting.

-

Authentication Systems: Logging into a corporate portal using either SAMLAuth, OAuth2Auth, or LocalDatabaseAuth.

Key Takeaway: The Strategy Pattern replaces inheritance and massive conditional blocks with composition. By delegating behaviors to interchangeable strategy objects, your code becomes highly modular, easier to test (you can mock individual strategies), and future-proof against shifting business requirements.

Subscribe now