Originally published on phpdesignpatterns.dev — part of the PHP design patterns course. View this lesson on the original site.

Reading other people's if-chains

You'll see other people's branch-heavy code in PRs and legacy files long before you have permission to refactor it. Here's a checklist for reading it well.

Read for the actual variation

When you open a function full of ifs, ask: what is varying between the branches?

  • An input value (currency, customer type, country code)? Strategy is plausible.
  • An output shape (sometimes returns a string, sometimes an array)? Probably not Strategy — possibly a missing abstraction.
  • The steps of the algorithm? Probably Template Method, not Strategy.
  • The state of an object? Probably State, not Strategy.

Spot the branch-naming smell

If every branch starts with // handle X or // special case for Y, the comments are class names trying to escape. Each // handle X is one Strategy class.

Spot the "default that lies"

<?php

default => null,

A default => null in a long match is often a missing strategy plus a missing decision about what to do when none applies. A reviewer flagging this in a PR is doing the team a favour.

Spot the silently-ordered conditions

<?php

if ($order->isInternational()) {
    // ...
}

if ($order->isUrgent()) {
    // ...
}

if ($order->isWholesale()) {
    // ...
}

These look independent but the order matters — an international urgent wholesale order can hit only the first branch. That's a bug waiting to bite. Strategy + a clear picker fixes it because the picker chooses one strategy, explicitly.

What to write in a review

Don't suggest "use Strategy". Suggest the underlying fix:

"Each of these branches is a customer-type rule. They tend to grow. Could we move each into its own class and look them up by type? Happy to help with the first one if useful."

That gives the author the option to push back if the variation isn't what you think it is — which is honest, because sometimes you'll be wrong.

From PHP design patterns — Strategy: replacing branching with swappable behaviour