Stop Writing If-Else Chains — Use Strategy Pattern Instead
Why long if-else chains are a code smell
If you've ever scrolled through a function with 15+ if / else if blocks, you know the pain. Every new condition makes the function longer, harder to test, and almost impossible to extend without introducing bugs.
The Strategy Pattern fix
Instead of branching on a type, map each type to a small handler object:
const strategies = {
credit: new CreditCardPayment(),
paypal: new PayPalPayment(),
crypto: new CryptoPayment(),
};
function processPayment(type, amount) {
return strategies[type].pay(amount);
}Adding a new payment method? Just add one new class and one key. Zero changes to processPayment.
When to use it
- You have 3+ branches that could each be their own "algorithm".
- You anticipate more branches in the future.
- You want each branch independently testable.
This single refactor can cut hundreds of lines and make your codebase dramatically cleaner. Try it on your next PR.
Comments
0
Loading comments…
No comments yet. Be the first to share your thoughts!