Strategy Pattern: when if/else starts running the business
How to use Strategy to isolate changing rules, reduce critical conditionals and turn business decisions into explicit policies.
- #gof
- #strategy
- #arquitectura
- #reglas-negocio
Executive summary
- Strategy helps when a variable rule starts running the business from scattered conditionals.
- The improvement is not aesthetic: it makes a business policy explicit, testable, and replaceable.
The real problem
The first if is not a problem. The tenth is. When pricing, permissions, scoring or validations change by segment, the main flow starts accumulating decisions nobody wants to touch.
The warning signal is simple: changing a business rule requires reading too much code that does not represent that rule.
What Strategy solves
Strategy defines a common interface for multiple policies and lets the system choose one at runtime. The decision becomes visible: which policy is used and why.
It does not remove business complexity. It places it in small, testable and replaceable objects.
How it looks in code
Checkout does not need to know every case. It only needs a policy with the right contract.
type DiscountStrategy = {
apply(total: number): number;
};
class Checkout {
constructor(private readonly discount: DiscountStrategy) {}
totalAfterDiscount(total: number) {
return this.discount.apply(total);
}
}
const noDiscount: DiscountStrategy = { apply: (total) => total };
const launchDiscount: DiscountStrategy = { apply: (total) => total * 0.9 };When to use it
Strategy makes sense when variability is already real:
- Pricing or discount rules change by segment.
- There are alternative validations for different channels.
- A calculation has multiple interchangeable algorithms.
- You need to test rules without booting the entire main flow.
When to avoid it
If there are only two stable branches and no evidence of change, a clear conditional may be better. Strategy adds names, files and composition; that cost must buy real flexibility.
Related evidence
FAQ
- Does Strategy replace every if?
- No. It replaces conditionals where the variation represents a policy or algorithm with its own lifecycle. A simple stable if may be the best option.
- What is the difference between Strategy and State?
- Strategy changes the selected algorithm. State changes behavior because the object is in a different internal state.