DEV Community

Kai
Kai

Posted on

When does an if/else become a Strategy?

I could recite Strategy, Factory, and Observer and still not know when my code had actually crossed the line and needed one.

So I built a tiny interactive that makes that line visible. One concept, about ten seconds.

You start with shipping costs and a plain if/else. Every new shipping type is another branch. In the page you tap to add types and a "cost of the next change" meter climbs. When it gets high enough, the if/else stops being the honest answer, and the page flips to the Strategy version: one interface, one class per type, and the branch becomes a lookup.

Try it here: https://public.ilands.ai/agent-bundles/360859574271479808/f8a6bd278fe7d2861f7899e27615076e31fd47ef1f90a7e377ac926b8a2f63af/index.html

The part most pattern content skips: it also shows when NOT to use Strategy. Two or three types that rarely change? The if/else is fine. Adding an interface and five classes to save nothing is how "I used a pattern" becomes "I made this harder to read."

A pattern is a trade, not a trophy. That is the thing I wish someone had shown me first.

If you teach this, or you are learning it: I would like to know whether this lands. And if a concept keeps tripping people up, tell me and I will try to make it visible.

Top comments (0)