SteelReed

Search

Search posts, questions…

3. Advanced Java

Design patterns through refactoring: Strategy

Learn Strategy by refactoring a data-sync class full of if/else: the starting smell, extracting the interface step by step, strategies as lambdas and functional interfaces, picking a strategy in Spring with a registry, and the traps around state, thread safety and rounding money.

18 Nov 20267 min readMid

–

1. The problem

A data sync component has an online flag, and the same if (online) appears in sync(), retry(), conflict(), progress(). Adding a "Wi-Fi only" mode means editing all four running methods; last time retry() was missed and data went over the customer's 4G.

2. Key idea

Patterns aren't something you "apply" up front: they show up after a specific smell, as the shared name for a fix. Strategy pulls "how to do it" into an interface with one class per way; the context holds one reference and just calls it. A new variant is a new class, no edits to old code (Open/Closed). But Strategy only moves the branching: something still decides which strategy to use, at startup (@ConditionalOnProperty), per request (a registry looked up by key), or on state changes (Observer).

Approach Use when Don't use when
if/else, switch 2–3 short branches, rarely changing, in one place the same question repeats across methods
Enum with abstract methods a closed set in one module (order states) variants need their own dependencies
Strategy an open set, own dependencies, swapped at runtime, needs mocking no smell yet: a one-implementation interface is over-engineering
A lambda as strategy short, stateless rules (discounts, sorting) long rules that deserve a name and their own tests

Wait for the second or third change of the same kind (rule of three) before extracting.

3. In Java

JAVA
interface SyncStrategy { void sync(String data); }
 
final class CloudSync implements SyncStrategy {
    public void sync(String data) { System.out.println("upload to cloud: " + data); }
}
 
final class DataSyncManager {
    private volatile SyncStrategy strategy;               // the context: one reference
    DataSyncManager(SyncStrategy s) { this.strategy = s; }
    void use(SyncStrategy s) { this.strategy = s; }
    void sync(String data) { strategy.sync(data); }
}
 
var manager = new DataSyncManager(new CloudSync());
manager.sync("prefs");                                     // upload to cloud: prefs
manager.use(data -> System.out.println("dry-run: " + data));  // a lambda is a strategy too
manager.sync("logs");                                      // dry-run: logs
 
// Composite: combine strategies, no class hierarchy needed
DiscountPolicy best = (subtotal, nights) -> longStay.discount(subtotal, nights).max(promo.discount(subtotal, nights));

Other languages: Go uses implicit interfaces or function types (type Pricing func(Order) Money); TypeScript passes functions or objects with methods.

Strategy in Spring: a registry checked at startup

Each strategy is a bean that declares its key; inject List<FeeStrategy>, build an EnumMap, and throw on duplicates or gaps so the app refuses to start with bad config.

JAVA
ShippingCalculator(List<FeeStrategy> all) {
    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);
}

Strategies shared across requests must be stateless. Per-user state goes in through parameters, or a new strategy per session.

4. Working with AI

Hand to AI: splitting an if/else into strategies, tests comparing old and new results over many inputs, a Spring registry checking duplicates and gaps.

Check yourself in AI-written code:

  • There's a real smell: the same question in several places, or a set of variants that will keep growing.
  • The choice of strategy lives in exactly one place.
  • Strategies that are singleton beans hold no per-user state.
  • The registry fails at startup on missing or duplicate keys.
  • There's a test comparing results with the old code before the old code is deleted.

5. Exercises

Exercise 1: Review the AI's LocalSync

The AI made LocalSync a @Component injected into DataSyncManager for every user, saying "proper Strategy, easy to test". User A sees user B's data in the offline queue, and there are occasional ArrayIndexOutOfBoundsExceptions with no clear source. Find the bugs and fix them.

JAVA
@Component
final class LocalSync implements SyncStrategy {
    private final List<String> pending = new ArrayList<>();
    public void sync(String data) { pending.add(data); }
}
Solution 1
  • A singleton bean shared by every user: A's and B's pending are the same list.
  • ArrayList isn't thread-safe; concurrent adds corrupt its internal array, producing ArrayIndexOutOfBoundsException.
  • Fix: a stateless strategy, with queues split per user in durable storage (a pending_sync(user_id, payload) table, or on-device storage). The strategy is only "how": sync(userId, data) writes to the right user's queue.

Exercise 2: Choose between an enum and Strategy

Shipping has three carriers: express 30,000 VND + 8,000/kg; economy 15,000 VND + 500/km, free from 500,000 VND; pickup free. Next year 4 more carriers are planned, each calling its own quoting API. The AI offers (A) an enum Carrier with an abstract fee(Parcel); (B) a FeeStrategy interface + a Spring registry. Pick one, give the reason and when the choice flips.

Solution 2

Pick B. New carriers need their own dependencies (HTTP clients, API keys), which an enum can't inject, and the set of carriers is open. The registry checks duplicates and gaps at startup, and a new carrier is just a new bean.

Pick A if the carriers are fixed and fees are pure formulas: the compiler forces every constant to implement the method, the code sits in one file, no Spring needed. Either way, round money in one place (setScale(0, HALF_UP) for VND) and test against the old function.

Summary

  • The Strategy smell: the same question repeated across methods.
  • Strategy pulls the "how" into an interface; the context holds one reference.
  • Strategy moves the branching to one place; it doesn't remove it.
  • if/else for a few fixed branches, enums for closed sets, Strategy for open sets.
  • Shared strategies must be stateless; registries check at startup.

Further reading: Template Method and composition.

Practice interview questions on this topic

All OOP & Design questions →

Loading comments…