Skip to content
notes.vinhnq.com

Search

OOP & DesignMid15 min read

Design patterns through refactoring: Strategy

Review 13 cards
On this page

Design patterns through refactoring series: 1. Strategy · 2. Template Method and composition · 3. Observer and Spring events · 4. Adapter and Factory

A pattern isn’t something you deliberately “apply” to code: it shows up after a specific smell, and it’s a shared name for a fix so a team can say it in two words (“make that a strategy”). This post refactors a data-sync class full of if/else into Strategy, then uses Strategy with lambdas and in Spring. Read first: Abstract classes and interfaces and IoC and Dependency Injection, since the Spring parts rely on constructor injection.

At a glance:

flowchart TD
  SM["Smell: same question repeated"] --> Q{Set of options?}
  Q -->|"2–3 fixed branches"| IF["if/else"]
  Q -->|closed set| EN[Enum with methods]
  Q -->|"open set / dependencies"| ST[Strategy]
  ST --> CTX[Context holds one reference]
  ST --> LB["Lambdas, composite"]
  ST --> SP["Spring: List → Map, check at startup"]
  SP -.->|trap| SF[Stateful shared strategy]

1. How to read a pattern in this series

Key idea: each pattern goes through four questions: what’s the smell, how do we refactor, what do we gain, what do we pay. Every pattern has a price.

Usually gained: new variants without editing existing code (the Open/Closed Principle — open for extension, closed for modification) and parts you can test in isolation. Usually paid: more classes, another layer of indirection (one more interface to jump through before the real code), logic spread over more files. The examples come from the course’s sample code, rewritten as my own code that runs on JDK 21.

Smell Pattern usually used to fix it Post
An if/else or switch on a “mode”, repeated across methods Strategy this one
Several flows with the same order of steps, differing in a few steps Template Method, or composition part 2
A class has to call every class that cares about its changes Observer part 3
A library’s interface doesn’t match the one you need Adapter part 4
Object creation scattered around, concrete new everywhere Factory part 4

2. Strategy: online/offline data sync

Key idea: a mobile app pushes data to the cloud when online and stores it on the device when offline. We turn each mode into a strategy so the sync class stops branching.

2.1. v0: one boolean, branches everywhere

Key idea: the smell isn’t “there’s an if”; it’s that the same question (online?) is asked in many places, and each mode is a chunk of behaviour big enough to live on its own.

The v0 code holds an online flag and every method branches on it. Adding a “Wi-Fi only” mode means editing a class that already works, which breaks Open/Closed.

The four drawbacks of v0, as listed by the sample repo’s author
  • Every call re-checks the network status.
  • Business logic is tied to the network mode.
  • The if/else keeps growing (sync, retry, conflict handling and progress reporting all branch).
  • Adding a “Wi-Fi only” mode means editing a class that already works, which breaks Open/Closed.
static class DataSyncManagerV0 {
    private boolean online;
    DataSyncManagerV0(boolean online) { this.online = online; }
    void setOnline(boolean online) { this.online = online; }

    void sync(String data) {
        if (online) {
            System.out.println("v0 upload to cloud: " + data);
        } else {
            System.out.println("v0 save locally: " + data);
        }
        // ...and the same if (online) again in retry(), conflict(), progress()...
    }
}

Strategy isn’t the only way out. For a closed set of variants, a sealed interface with a pattern-matching switch, or guard clauses (handle the edge case and return early), are sometimes enough and simpler; see Clean code: naming, functions and control flow (plus SRP/OCP at the class level).

2.2. Refactor: the varying part becomes an interface

Key idea: “how to do it” becomes an interface with one class per way, and the object using it (the context) holds just a reference and calls it directly.

interface SyncStrategy {
    void sync(String data);
}

static final class CloudSync implements SyncStrategy {
    public void sync(String data) { System.out.println("upload to cloud: " + data); }
}

static final class LocalSync implements SyncStrategy {
    private final List<String> pending = new java.util.ArrayList<>();
    public void sync(String data) {
        pending.add(data);
        System.out.println("queued locally (" + pending.size() + " pending): " + data);
    }
}

static final class DataSyncManager {
    private volatile SyncStrategy strategy;            // swapped at runtime by another thread
    DataSyncManager(SyncStrategy initial) { this.strategy = initial; }
    void use(SyncStrategy next) { this.strategy = next; }
    void sync(String data) { strategy.sync(data); }   // no if/else left here
}
var manager = new DataSyncManager(new CloudSync());
manager.sync("prefs");
manager.use(new LocalSync());
manager.sync("images");
manager.use(data -> System.out.println("dry-run, would sync: " + data)); // a lambda is a strategy too
manager.sync("logs");
upload to cloud: prefs
queued locally (1 pending): images
dry-run, would sync: logs
  • Gained: DataSyncManager doesn’t know how many modes exist; “Wi-Fi only” is just one new class; each strategy can be tested on its own.
  • Paid: three more types, and a reader has to jump between files to find out what “sync” actually does.

2.3. Strategy moves the branch; it doesn’t delete it

Key idea: the “which strategy?” decision still has to happen somewhere; put it in exactly one place, never repeated at every call site.

In the sample repo, after the refactor, main still checks the network itself and calls setSyncStrategy, repeated every time the status changes. There are three sensible places for the decision:

2.4. Strategy in modern Java: functional interfaces and lambdas

Key idea: a strategy with a single method is a functional interface, so a lambda is a strategy, and combining strategies is just ordinary code.

Take booking discounts (the sample repo has a DiscountService giving 5% off stays of 3 nights or more):

@FunctionalInterface
interface DiscountPolicy {
    /** Returns a non-negative discount amount. */
    BigDecimal discount(BigDecimal subtotal, int nights);

    DiscountPolicy NONE = (subtotal, nights) -> BigDecimal.ZERO;

    static DiscountPolicy longStay(int minNights, String rate) {
        BigDecimal r = new BigDecimal(rate);
        return (subtotal, nights) -> nights >= minNights ? subtotal.multiply(r) : BigDecimal.ZERO;
    }

    /** Policies don't stack: the guest gets the best one. */
    static DiscountPolicy bestOf(List<DiscountPolicy> policies) {
        return (subtotal, nights) -> policies.stream()
                .map(p -> p.discount(subtotal, nights))
                .max(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
    }
}

record Price(BigDecimal subtotal, BigDecimal discount, BigDecimal total) {}

static Price price(List<BigDecimal> nightly, DiscountPolicy policy) {
    BigDecimal subtotal = nightly.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
    BigDecimal discount = policy.discount(subtotal, nightly.size()).setScale(2, RoundingMode.HALF_EVEN);
    return new Price(subtotal, discount, subtotal.subtract(discount));
}

bestOf is a composite strategy: a strategy built from other strategies, with no extra class hierarchy.

Running DiscountPolicy and its output
var nightly = List.of(new BigDecimal("33.33"), new BigDecimal("33.33"), new BigDecimal("33.34"));
System.out.println(price(nightly, DiscountPolicy.NONE));
System.out.println(price(nightly, DiscountPolicy.longStay(3, "0.05")));
var best = DiscountPolicy.bestOf(List.of(DiscountPolicy.longStay(3, "0.05"), DiscountPolicy.longStay(7, "0.12")));
System.out.println(price(nightly, best));

BigDecimal raw = new BigDecimal("100.00").multiply(BigDecimal.valueOf(-0.05));
System.out.println("raw negative discount = " + raw + " (scale " + raw.scale() + ")");
Price[subtotal=100.00, discount=0.00, total=100.00]
Price[subtotal=100.00, discount=5.00, total=95.00]
Price[subtotal=100.00, discount=5.00, total=95.00]
raw negative discount = -5.0000 (scale 4)

2.5. Strategy in Spring

Key idea: Spring injects every bean implementing an interface as a List (or a Map<String, T> keyed by bean name); the service builds a registry by key, and configuration mistakes surface at startup.

The usual shape (it needs Spring, so I didn’t run it for this post):

public interface DiscountPolicy {
    String code();                                   // "LONG_STAY", "EARLY_BIRD"...
    BigDecimal discount(BigDecimal subtotal, int nights);
}

@Service
public class PricingService {
    private final Map<String, DiscountPolicy> policies;

    public PricingService(List<DiscountPolicy> all) {             // Spring injects every DiscountPolicy bean
        this.policies = all.stream().collect(Collectors.toUnmodifiableMap(DiscountPolicy::code, p -> p));
        // toUnmodifiableMap throws IllegalStateException on duplicate codes: a startup error, not a runtime one
    }

    public BigDecimal discountFor(String code, BigDecimal subtotal, int nights) {
        var policy = policies.get(code);
        if (policy == null) throw new IllegalArgumentException("unknown discount " + code);
        return policy.discount(subtotal, nights);
    }
}

Two other options: @Qualifier("longStay") when the call site always uses one strategy, and @ConditionalOnProperty when configuration picks the strategy for the whole application (for example storage.mode=s3|local).

Registry detail: toMap throws on duplicate keys

Exercises

Exercise 1: Refactor shipping fees into Strategy

Task (paraphrased): a method computes shipping fees with if/else for three carriers: express charges 30,000 VND + 8,000/kg; economy charges 15,000 + 500/km and is free for orders of 500,000 or more; in-store pickup is free. Turn it into Strategy chosen by carrier, so a new carrier needs no edits to existing code and missing configuration is caught at startup. Results must match the old code exactly.

Solution to Exercise 1: an EnumMap registry that checks duplicates and gaps
interface FeeStrategy {
    Carrier carrier();
    BigDecimal fee(Parcel p);
}

static final class ExpressFee implements FeeStrategy {
    public Carrier carrier() { return Carrier.EXPRESS; }
    public BigDecimal fee(Parcel p) { return new BigDecimal("30000").add(p.weightKg().multiply(new BigDecimal("8000"))); }
}

static final class EconomyFee implements FeeStrategy {
    private static final BigDecimal FREE_FROM = new BigDecimal("500000");
    public Carrier carrier() { return Carrier.ECONOMY; }
    public BigDecimal fee(Parcel p) {
        if (p.orderValue().compareTo(FREE_FROM) >= 0) return BigDecimal.ZERO;
        return new BigDecimal("15000").add(BigDecimal.valueOf(p.distanceKm()).multiply(new BigDecimal("500")));
    }
}

static final class PickupFee implements FeeStrategy {
    public Carrier carrier() { return Carrier.PICKUP; }
    public BigDecimal fee(Parcel p) { return BigDecimal.ZERO; }
}

static final class ShippingCalculator {
    private final Map<Carrier, FeeStrategy> strategies = new EnumMap<>(Carrier.class);

    ShippingCalculator(List<FeeStrategy> all) {                 // in Spring: constructor-inject List<FeeStrategy>
        all.forEach(s -> {
            if (strategies.put(s.carrier(), s) != null) throw new IllegalStateException("duplicate " + s.carrier());
        });
        for (Carrier c : Carrier.values())
            if (!strategies.containsKey(c)) throw new IllegalStateException("missing " + c);
    }

    BigDecimal fee(Carrier c, Parcel p) {
        return strategies.get(c).fee(p).setScale(0, RoundingMode.HALF_UP);   // VND: whole dong
    }
}

Compared against the old method on two parcels (1.25 kg/12 km/200,000 order and 3 kg/40 km/650,000 order), with no MISMATCH line:

EXPRESS  1.25kg/12km -> 40000
ECONOMY  1.25kg/12km -> 21000
PICKUP   1.25kg/12km -> 0
EXPRESS  3kg/40km -> 54000
ECONOMY  3kg/40km -> 0
PICKUP   3kg/40km -> 0
  • Each strategy declares which carrier it serves (carrier()), so the registry needn’t know the list of carriers.
  • The duplicate and missing checks in the constructor turn configuration mistakes into startup failures.
  • What a senior adds: characterization tests comparing old and new code on many random inputs before deleting the old code; moving the numbers (30,000, 8,000…) into versioned configuration if the business changes prices often.

Remember

  • Point out which smell is worth a Strategy, and why “there’s an if” isn’t one yet.
  • Know where the “which strategy?” decision belongs: configuration, a registry or an Observer.
  • Choose between if/else, an enum with behaviour and Strategy for a concrete case.
  • Explain why shared strategies must be stateless in Spring.
  • Build a Spring strategy registry whose duplicates and gaps fail at startup.

Interview questions

Junior

What is the Strategy pattern? Give a backend example.

Strategy pulls a behaviour with several implementations out into an interface, one implementation per variant; the object using it only holds a reference to the interface.

Examples: discount rules (long stay, early bird, voucher), shipping fees by carrier, where to store files (S3 or local disk). A new variant is a new class, with no edits to the code that uses it.

What does the Open/Closed Principle mean?

Code should be “open for extension, closed for modification”: add behaviour by adding code (a new class, a new bean), not by editing code that already works.

Strategy and Template Method are two common ways to get there. It isn’t absolute: apply it where things actually change often.

Mid

In Spring, how do you pick a strategy based on request data?

Each strategy is a bean that declares its own key; the service receives List<Strategy> through its constructor, builds a Map/EnumMap from key to bean, and at runtime it’s just map.get(key).

Check for duplicates and gaps right in the constructor, so configuration mistakes surface at startup. That avoids a switch you’d edit for every new type.

What goes wrong with a stateful strategy as a Spring bean?

Beans are singletons by default, shared by every request and thread, so state inside a strategy mixes data between requests and hits race conditions.

Strategies should be stateless. If you need per-use state, create a new instance (a factory or prototype scope) or pass the state as parameters.

When do you use an enum with behaviour instead of Strategy?

When the set of variants is closed, lives in the same module and has no dependencies of its own, like order states or fixed fee types.

Each enum constant implements the method and the compiler makes sure all of them do. Once a variant needs injected beans (a repository, a client), has to be added from another module, or changes at runtime, switch to an interface and Strategy beans.

Senior

How would you refactor a 300-line method full of type checks into a pattern without breaking production?

Pin the current behaviour down with characterization tests first, then move the branches out in many small PRs with green tests, and never mix the refactor with a business change.

  • Characterization tests record behaviour over many inputs, including “wrong” behaviour the system relies on.
  • Split the method into small steps without changing behaviour, then move each type branch into its own implementation.
  • You can run old and new code side by side and compare results (shadowing) before deleting the old code.
Strategy moves the “which way?” decision somewhere. Where do you put it?

Strategy removes the if/else from the context, but the decision still has to live in exactly one place.

  • The whole application uses one way: startup configuration (@ConditionalOnProperty, profiles).
  • Each request differs: a registry looked up by request data.
  • The choice follows system state (network, a feature flag): an Observer.

What I avoid is repeating the decision at every call site, because then the old smell has just moved.

Useful phrases for interviews

  • “The smell wasn’t the if itself; it was the same question being asked in five different methods.”
  • “Strategy doesn’t remove the decision, it moves it to one place: a registry, a config property or an observer.”
  • “Each strategy declares its own key, and the registry fails at startup if a type is missing.”
  • “Shared strategies should be stateless, because Spring beans are singletons by default.”
  • “For two branches that never change, a plain if is cheaper than a strategy interface.”
  • “We round money once, in one place, to the currency’s number of decimals.”
  • “Before refactoring legacy code, I pin its behaviour down with characterization tests.”

Notes based on the Advanced Backend course (Ronin Engineer), rewritten in my own words.