Strategy Pattern: Replacing Conditional Logic
The Strategy Pattern is more than a way to replace `if/else` statements. Learn how to isolate interchangeable behaviors, simplify testing, separate strategy selection from execution, and decide when an abstraction is worth the cost.
Table of Contents
- Introduction
- 1. When Conditional Logic Becomes a Design Problem
- 2. The Core Idea Behind Strategy
- 3. A Practical Example: Payment Processing
- 4. What Changes After Applying Strategy
- 5. Selecting a Strategy Is a Separate Problem
- 6. Strategy Pattern and the Open/Closed Principle
- 7. Testing Strategies Independently
- 8. When Strategy Is Not the Right Choice
- 9. Strategy vs. Related Patterns
- Summary
Introduction
Conditional logic is not inherently bad.
An if statement is often the simplest and clearest way to express a decision. A switch statement can make multiple cases easy to understand. There is no reason to replace them with abstractions when the logic is small, stable, and unlikely to change.
The problem begins when conditional logic becomes the place where an application manages multiple variations of the same behavior.
As new requirements arrive, the same conditions appear in multiple places. Adding a new option requires modifying existing code, tests become harder to organize, and one class gradually takes responsibility for understanding every variation.
This is where the Strategy Pattern becomes useful.
The Strategy Pattern is not simply a technique for removing if/else statements. It is a way to separate interchangeable behaviors from the code that uses them, allowing each behavior to evolve independently while the surrounding workflow remains stable.
Understanding when that separation is valuable matters more than memorizing the pattern's structure.
1. When Conditional Logic Becomes a Design Problem
Consider an application that calculates shipping costs.
Initially, it supports two shipping methods:
type ShippingMethod = "standard" | "express";
function calculateShipping(
method: ShippingMethod,
weight: number,
): number {
if (method === "standard") {
return weight * 2;
}
if (method === "express") {
return weight * 5;
}
throw new Error("Unsupported shipping method");
}This implementation is perfectly reasonable.
The behavior is small, easy to read, and contained in one function. Introducing an interface and multiple classes would add complexity without providing much value.
Now imagine the requirements change.
The application introduces international shipping, different pricing rules for different regions, seasonal surcharges, and special handling for certain products. Other parts of the application also need to calculate shipping costs.
The original function may gradually evolve into something like this:
function calculateShipping(
method: string,
weight: number,
destination: string,
isFragile: boolean,
): number {
if (method === "standard") {
// Standard shipping rules
} else if (method === "express") {
// Express shipping rules
} else if (method === "international") {
// International shipping rules
}
// Additional regional and product-specific conditions
throw new Error("Shipping calculation not implemented");
}The issue is not the number of conditions alone. It is the number of responsibilities accumulating inside the function.
The function now needs to know:
- Which shipping methods exist.
- How each method calculates its price.
- Which rules apply to each destination.
- How special cases interact with the calculation.
- What must change when a shipping method is introduced or modified.
Every new variation potentially affects code that already works.
The design question becomes:
Should one function know every shipping algorithm, or should each algorithm own its own rules?
That is the problem the Strategy Pattern helps address.
2. The Core Idea Behind Strategy
The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable through a common interface.
There are three essential parts:
- Strategy: A contract describing the behavior that can vary.
- Concrete strategies: Independent implementations of that behavior.
- Context: The component that uses a strategy without needing to know its internal implementation.
The relationship looks like this:
classDiagram
class ShippingStrategy {
<<interface>>
+calculate(weight: number) number
}
class StandardShipping {
+calculate(weight: number) number
}
class ExpressShipping {
+calculate(weight: number) number
}
class ShippingService {
-strategy: ShippingStrategy
+calculate(weight: number) number
}
ShippingStrategy <|.. StandardShipping : implements
ShippingStrategy <|.. ExpressShipping : implements
ShippingService --> ShippingStrategy : delegates toThe important design decision is not that the implementation uses interfaces or classes. It is that the service depends on a stable contract rather than directly managing every algorithm.
In TypeScript, the strategy contract might be:
interface ShippingStrategy {
calculate(weight: number): number;
}Every shipping strategy must implement the same operation, but each is free to use its own calculation rules.
class StandardShipping implements ShippingStrategy {
calculate(weight: number): number {
return weight * 2;
}
}
class ExpressShipping implements ShippingStrategy {
calculate(weight: number): number {
return weight * 5;
}
}The context delegates the calculation to whichever strategy it receives:
class ShippingService {
constructor(
private readonly strategy: ShippingStrategy,
) {}
calculate(weight: number): number {
return this.strategy.calculate(weight);
}
}Usage:
const standardShipping = new ShippingService(
new StandardShipping(),
);
const expressShipping = new ShippingService(
new ExpressShipping(),
);
console.log(standardShipping.calculate(10)); // 20
console.log(expressShipping.calculate(10)); // 50The service does not need to know how standard or express shipping works. It only needs to know that the selected strategy can calculate a shipping cost.
This is the central idea:
Keep the workflow stable while allowing the behavior it delegates to vary.
3. A Practical Example: Payment Processing
Shipping calculations demonstrate the basic structure. Payment processing shows why the pattern can become more valuable as a system grows.
Suppose an application supports Stripe and PayPal.
A straightforward implementation might look like this:
type PaymentProvider = "stripe" | "paypal";
async function processPayment(
provider: PaymentProvider,
amount: number,
): Promise<void> {
if (provider === "stripe") {
// Validate Stripe-specific data
// Call the Stripe API
// Handle the Stripe response
} else if (provider === "paypal") {
// Validate PayPal-specific data
// Call the PayPal API
// Handle the PayPal response
} else {
throw new Error("Unsupported payment provider");
}
}The function now contains multiple provider-specific workflows. As integrations become more complicated, each branch may involve different request formats, authentication mechanisms, error responses, and retry rules.
Adding another provider means modifying the function and potentially expanding its tests.
The first step is to identify what genuinely varies.
In this example, each provider must support a common operation: processing a payment.
Define the strategy contract
interface PaymentStrategy {
processPayment(amount: number): Promise<void>;
}This contract describes what the application needs from a payment provider. It does not expose how that provider communicates with its external API.
Implement concrete strategies
class StripePaymentStrategy implements PaymentStrategy {
async processPayment(amount: number): Promise<void> {
// Build a Stripe request
// Call Stripe
// Interpret the response
}
}
class PayPalPaymentStrategy implements PaymentStrategy {
async processPayment(amount: number): Promise<void> {
// Build a PayPal request
// Call PayPal
// Interpret the response
}
}These implementations are illustrative. A production integration would also need appropriate authentication, validation, idempotency, error handling, and payment-state management.
The important point is that provider-specific behavior now lives in separate components.
Keep the payment workflow independent
class PaymentService {
constructor(
private readonly strategy: PaymentStrategy,
) {}
async pay(amount: number): Promise<void> {
if (amount <= 0) {
throw new Error("Payment amount must be positive");
}
await this.strategy.processPayment(amount);
}
}The service owns the shared validation and delegates provider-specific processing.
Usage:
const paymentService = new PaymentService(
new StripePaymentStrategy(),
);
await paymentService.pay(100);Switching to PayPal requires a different strategy:
const paymentService = new PaymentService(
new PayPalPaymentStrategy(),
);
await paymentService.pay(100);The payment workflow remains unchanged.
Notice the boundary: the example assumes that the strategy has already been selected. Choosing a provider based on an order, a user's preference, or a business rule is a separate design concern, which we will examine later.
What if providers have different capabilities?
A shared interface is useful only when it expresses a meaningful common contract.
Suppose one provider supports refunds while another does not. There are several possible approaches:
- Define a separate refund capability.
- Use separate interfaces for payment and refund operations.
- Model provider capabilities explicitly.
- Reject unsupported operations through a clearly defined application-level contract.
Do not force every provider to implement meaningless methods just to make the class hierarchy look uniform.
Strategy works best when the shared contract represents behavior that consumers genuinely need.
4. What Changes After Applying Strategy
The benefit is not simply that the conditional statement disappears. The design changes how responsibilities are distributed.
| Before Strategy | After Strategy |
|---|---|
| One component knows every algorithm | Each strategy owns its algorithm |
| Adding behavior often modifies the central function | New implementations can often be added independently |
| Tests may need to exercise many branches together | Strategies can be tested in isolation |
| Provider-specific changes can affect shared workflow code | Provider changes are more localized |
| Selection and execution may be mixed together | Selection can be separated from execution |
These are potential benefits, not automatic guarantees. Poorly designed strategies can still share too much state, duplicate logic, or depend on the same unstable components.
The real improvement comes from creating a boundary that matches the way the behavior changes.
Independent evolution
Imagine that Stripe changes its request format.
With provider-specific logic encapsulated in StripePaymentStrategy, the change can usually remain within that implementation.
The shared PaymentService should not need to understand the new request format.
Similarly, adding a new provider can often mean implementing the existing contract instead of editing every place where payments are processed.
This reduces the number of components that need to change together.
Independent testing
Each strategy can be tested against its own behavior and edge cases. The context can be tested using a fake strategy without contacting an external payment provider.
class FakePaymentStrategy implements PaymentStrategy {
public lastAmount: number | undefined;
async processPayment(amount: number): Promise<void> {
this.lastAmount = amount;
}
}A test can then verify delegation and shared validation without requiring a real integration.
const fakeStrategy = new FakePaymentStrategy();
const service = new PaymentService(fakeStrategy);
await service.pay(100);
if (fakeStrategy.lastAmount !== 100) {
throw new Error("Payment was not delegated correctly");
}In a real test suite, use a testing framework and assertions rather than manually throwing errors.
Strategy does not eliminate integration testing. It makes it easier to test the boundaries separately.
5. Selecting a Strategy Is a Separate Problem
One of the most common mistakes when applying Strategy is assuming that the pattern automatically eliminates every conditional statement.
It does not.
Consider this code:
function createPaymentStrategy(
provider: PaymentProvider,
): PaymentStrategy {
switch (provider) {
case "stripe":
return new StripePaymentStrategy();
case "paypal":
return new PayPalPaymentStrategy();
default:
throw new Error("Unsupported payment provider");
}
}The conditional logic still exists. It has simply moved to the component responsible for selecting a strategy.
That can be a good design.
The key is that the conditional now has a narrower responsibility: choosing an implementation. It no longer contains the implementation details of every payment provider.
flowchart LR
A["Provider identifier<br/>(e.g. "stripe")"] --> B["Selection<br/>switch / registry"]
B --> C["PaymentStrategy<br/>instance"]
C --> D["PaymentService.pay()"]
D --> E["strategy.processPayment()"]
subgraph Selection
B
end
subgraph Execution
D
E
endFor a small, fixed set of strategies, a switch statement may be the clearest solution.
If strategies are registered dynamically or the number of implementations grows, a registry can be more appropriate:
class PaymentStrategyRegistry {
private readonly strategies = new Map<
PaymentProvider,
PaymentStrategy
>();
register(
provider: PaymentProvider,
strategy: PaymentStrategy,
): void {
this.strategies.set(provider, strategy);
}
get(provider: PaymentProvider): PaymentStrategy {
const strategy = this.strategies.get(provider);
if (!strategy) {
throw new Error(`Unsupported payment provider: ${provider}`);
}
return strategy;
}
}Example:
const registry = new PaymentStrategyRegistry();
registry.register("stripe", new StripePaymentStrategy());
registry.register("paypal", new PayPalPaymentStrategy());
const strategy = registry.get("stripe");
const service = new PaymentService(strategy);
await service.pay(100);A registry is not automatically better than a switch. It adds registration and lookup mechanics, which are worthwhile only when the system benefits from them.
For a larger application, dependency injection may construct and register these strategies. For a small application, direct construction may be enough.
There is no requirement to introduce a factory, a registry, or a dependency injection container just because Strategy is being used.
Separate behavior from selection, but do not build a selection framework without a real need.
6. Strategy Pattern and the Open/Closed Principle
The Open/Closed Principle states that software entities should be open for extension but closed for modification.
Strategy can help achieve this by allowing new implementations to be introduced through an existing contract.
For example, adding a new payment provider may require only a new implementation:
class BankTransferPaymentStrategy implements PaymentStrategy {
async processPayment(amount: number): Promise<void> {
// Implement bank transfer processing
}
}The shared payment workflow does not need to change if the new strategy fits the existing contract.
However, there is an important limitation.
If the application uses a hard-coded switch to select every provider, adding a provider still requires modifying that selection logic. Strategy has isolated the algorithms, but it has not made the entire system closed to modification.
That is not necessarily a failure. Some selection points are expected to change.
The goal is not to eliminate all modifications. The goal is to keep changes localized and avoid forcing unrelated components to change together.
You should also avoid making an interface artificially generic in anticipation of every possible future variation. A contract that is too broad can become difficult to implement and maintain.
Design for known variation, then introduce additional abstraction when actual requirements justify it.
7. Testing Strategies Independently
One of Strategy's most useful practical benefits is that different behaviors can be tested without repeatedly exercising the entire application.
For the payment example, tests can be organized around three responsibilities.
Concrete strategy tests
Verify each provider's request construction, response handling, and error mapping. External API calls should normally be mocked in unit tests, with separate integration tests covering the real boundary.
Context tests
Verify shared behavior such as amount validation and correct delegation. Use a fake strategy to isolate the context.
Selection tests
Verify that a provider identifier maps to the expected strategy and that unsupported identifiers are handled correctly.
This separation makes test failures easier to interpret.
If a Stripe request is malformed, the relevant strategy test should identify the issue. If an invalid amount is accepted, the context test should catch it. If the wrong provider is selected, the selection test should expose that defect.
The pattern does not automatically make code testable. Its value is that it gives the code distinct responsibilities that can be tested independently.
8. When Strategy Is Not the Right Choice
A design pattern introduces structure. That structure must earn its cost.
The behavior is small and stable
If a function contains two simple branches that rarely change, the conditional version may be easier to understand.
function calculateDiscount(isMember: boolean): number {
return isMember ? 0.1 : 0;
}Creating an interface and multiple strategy classes for this function would probably make the design worse.
The variations are not truly interchangeable
Strategy assumes that the different implementations can serve the same role through a common contract.
If two workflows have fundamentally different inputs, outputs, side effects, or business meanings, forcing them behind one interface may hide important differences.
In that case, separate use cases or explicit domain operations may be clearer.
The abstraction creates unnecessary indirection
If developers must jump through several interfaces, factories, registries, and classes to understand a tiny calculation, the architecture may be more complicated than the problem.
The question is not whether the design follows a pattern. The question is whether it reduces the complexity that developers actually have to manage.
The conditional expresses a domain decision
Consider:
if (order.total > 1000) {
requireManualApproval(order);
}This condition may represent a business rule, not interchangeable behavior.
Turning every business condition into a strategy can make simple domain rules harder to read. Strategy becomes useful when there are genuinely different algorithms or policies that need to be selected and evolved independently.
The variation belongs in configuration or data
If the only difference between implementations is a rate or threshold, a configuration object or data-driven rule may be more appropriate than separate classes.
For example, shipping rates that differ only by a multiplier might be represented as data:
const shippingRates = {
standard: 2,
express: 5,
} as const;
type ShippingMethod = keyof typeof shippingRates;
function calculateShipping(
method: ShippingMethod,
weight: number,
): number {
return shippingRates[method] * weight;
}This approach keeps the code simple because the variation is data, not a distinct algorithm.
Use Strategy when behavior varies. Use configuration when the behavior is the same but its parameters differ.
That distinction can prevent a large amount of unnecessary abstraction.
9. Strategy vs. Related Patterns
Strategy is often confused with other patterns because several of them use interfaces, composition, or interchangeable components.
Their intent, however, is different.
| Pattern | Primary question |
|---|---|
| Strategy | Which behavior or algorithm should be used? |
| Factory | Who is responsible for creating an object? |
| Dependency Injection | How does a component receive its dependencies? |
| State | How does behavior change according to an object's current state? |
| Decorator | How can behavior be extended by wrapping an existing component? |
These patterns can work together, but they solve different problems.
A factory might create a StripePaymentStrategy. Dependency injection might supply it to PaymentService. Strategy defines the interchangeable payment behavior itself.
A State Pattern implementation may also delegate behavior, but its selection is usually driven by the object's current state and its transitions rather than by choosing among independent algorithms for a task.
Do not choose a pattern because its structure looks similar to your code. Choose it because its intent matches the design problem you need to solve.
Summary
The Strategy Pattern helps when an application contains multiple interchangeable implementations of the same behavior and those implementations need to evolve independently.
Its value is not the elimination of if/else statements. It is the separation of responsibilities:
- The strategy defines a common behavioral contract.
- Concrete strategies encapsulate individual algorithms.
- The context delegates work without depending on each implementation's internal details.
- A separate selection mechanism chooses the appropriate strategy when necessary.
The pattern also introduces costs: more components, additional indirection, and potentially more complex object creation and selection. Those costs are justified when the separation makes change, testing, and maintenance easier.
Before applying Strategy, ask three questions:
- Is the behavior likely to vary independently?
- Do the variations share a meaningful contract?
- Will separating them reduce complexity more than it adds?
If the answer to these questions is yes, Strategy may be a good fit.
If the behavior is small, stable, or primarily data-driven, a simple conditional or configuration object may be better.
Learn the problem before choosing the pattern. Separate behavior when the separation has value—not simply because a conditional statement exists.
- Design Patterns
- Strategy Design Pattern
- Software Design
- OOP
- Programing
- Software Architecture