If you have ever opened a file and been greeted by a case statement so tall it needs its own zip code, congratulations: you have met the exact problem the Strategy Pattern was invented to fix.
Every codebase has one of these functions. It started out innocent—maybe 12 lines, two if branches, and a developer saying "we'll clean this up later." Three years and fourteen product-manager "quick tweaks" later, nobody dares touch it without lighting a candle first.
I first ran into the Strategy Pattern shortly after landing at USC. My senior lead suggested we use it for a feature we were building—and after nodding like I definitely knew what that meant, I realized it was actually one of the cleanest tricks in the book.
What is the Strategy Pattern, actually?
Strip away the Gang of Four textbook jargon and the Strategy Pattern is embarrassingly simple: instead of stuffing every possible way to do a job into one mega-function, you split each approach into its own tiny, self-contained thing and pass in the one you want.
That's it. You're basically telling your function: "Stop trying to know everything. Just run the playbook I hand you."
Scenario One
Picture a Rails service calculating shipping at checkout. Day one, life is good. You have Standard and Express:
def calculate_shipping(method, order)
case method
when :standard
order.weight * 1.5
when :express
order.weight * 3.0 + 10
when :overnight
order.weight * 5.0 + 25
when :drone_maybe_on_tuesdays
order.weight < 5 ? 18 : 99
when :vip_best_friend_discount
0
else
raise ArgumentError, "Congratulations, you invented a shipping method: #{method}"
end
end
Every time marketing invents a new shipping tier, you have to crack open calculate_shipping, pray you don't break :overnight while adding :drone_maybe_on_tuesdays, and re-test the entire universe.
Enter the Strategy Pattern
With the Strategy Pattern, each shipping rule gets its own neat little class (or callable object) and stops bothering everyone else:
module Shipping
class Standard
def call(order) = order.weight * 1.5
end
class Express
def call(order) = order.weight * 3.0 + 10
end
class Overnight
def call(order) = order.weight * 5.0 + 25
end
class Pickup
def call(_order) = 0
end
end
class ShippingCalculator
def initialize(strategy:)
@strategy = strategy
end
def call(order)
@strategy.call(order)
end
end
# Usage
cost = ShippingCalculator.new(strategy: Shipping::Express.new).call(order)
Why bother?
- You stop breaking old things when adding new things. New shipping tier? Add a new strategy. Leave the existing ones completely alone.
- Unit tests stop being a hostage situation. You can test
overnightin three lines without mocking half the checkout pipeline. - Swap behaviors at runtime. Pick a strategy from user input, a feature flag, or a config file without littering your core logic with
if beta_user? && !Date.today.friday?. - Cleaner mental model. The caller decides when something happens; the strategy decides how.