DevPrep

All topics › Design patterns

Strategy: how do you swap an algorithm without if/switch all over the code?

Middle PRO

The gist

Strategy is a family of interchangeable algorithms behind a common interface. The client receives a strategy from outside and simply calls it, without knowing which one it got. Instead of switch userType in ten places you keep one point of choice (a factory, a config, a feature flag in the composition root), and the rest of the code is polymorphic.

In Swift a strategy takes three forms: a protocol — when the algorithm has parameters, state, dependencies or several methods; a closure — a single function without configuration; an enum — the set of variants is closed and known in advance.

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store