Strategy

Mid-level Always asked 6 min

On this page

The question

How would you remove a long if/else or switch from a method?

30-second answer

If each branch is a different way of doing the same job, turn each branch into a Strategy: one interface with one implementation per case. The method then looks the strategy up, in a Map or from injected beans, and calls it. A new case becomes a new class instead of an edit to a tested method. Two stable branches can stay a plain if.

Understand it

Swap the discount at runtime

Explore

Checkout calls discount.apply(100). The "10% off" strategy returns $90, and Checkout's code did not change.

100 $
View as text

A Checkout box stays fixed at the top, and an arrow joins it to one of four discount strategies below. A slider sets the order total, and the amount Checkout charges appears at the bottom.

Checkout calls discount.apply(100). The "None" strategy returns $100, and Checkout's code did not change. The None box is selected.

Checkout calls discount.apply(100). The "10% off" strategy returns $90, and Checkout's code did not change. The 10% box is selected.

Checkout calls discount.apply(10). The "$15 off" strategy returns $0, and Checkout's code did not change. The discount stops at zero rather than going negative.

Checkout calls discount.apply(200). The "Half" strategy returns $100, and Checkout's code did not change. A badge reads Checkout edits: 0 in every case.

A Checkout box stays fixed at the top, and an arrow joins it to one of four discount strategies below. A slider sets the order total, and the amount Checkout charges appears at the bottom.

Checkout calls discount.apply(100). The "None" strategy returns $100, and Checkout's code did not change. The None box is selected.

Checkout calls discount.apply(100). The "10% off" strategy returns $90, and Checkout's code did not change. The 10% box is selected.

Checkout calls discount.apply(10). The "$15 off" strategy returns $0, and Checkout's code did not change. The discount stops at zero rather than going negative.

Checkout calls discount.apply(200). The "Half" strategy returns $100, and Checkout's code did not change. A badge reads Checkout edits: 0 in every case.

Takeaway: Checkout depends on one interface, so choosing another strategy changes the result and never changes Checkout.

Add a discount: if/else vs strategy map

Compare

if/else: every discount lives inside Checkout. Adding Half means editing that method, so every existing branch needs testing again.

View as text

One Checkout box, with a new Half discount being added, and three rows below it: whether Checkout must be edited, what to retest, and whether the behavior can be swapped at runtime.

if/else: every discount lives inside Checkout. Adding Half means editing that method, so every existing branch needs testing again. The box holds three if branches, and the new one is marked as an edit. The rows read yes, every branch, and no.

Strategy map: each discount is a class or lambda, and Checkout only looks one up. Adding Half adds a class and one entry, with no edit to Checkout. The box holds one lookup line with the three discounts as separate classes below it, and the new one is marked as added. The rows read no, the new class, and yes.

One Checkout box, with a new Half discount being added, and three rows below it: whether Checkout must be edited, what to retest, and whether the behavior can be swapped at runtime.

if/else: every discount lives inside Checkout. Adding Half means editing that method, so every existing branch needs testing again. The box holds three if branches, and the new one is marked as an edit. The rows read yes, every branch, and no.

Strategy map: each discount is a class or lambda, and Checkout only looks one up. Adding Half adds a class and one entry, with no edit to Checkout. The box holds one lookup line with the three discounts as separate classes below it, and the new one is marked as added. The rows read no, the new class, and yes.

Takeaway: A growing if/else concentrates every change in one method; a map of strategies turns each new case into a new entry and leaves the method alone.

Strategy or StateIf there are only two stable cases, a plain if is enough. If cases grow and the caller picks a behavior, it is Strategy. If the object changes its behavior as its own state changes, it is State.Who picks thebehavior?Two stable cases:a plain ifThe caller:StrategyThe object itself:State
Strategy or StateIf there are only two stable cases, a plain if is enough. If cases grow and the caller picks a behavior, it is Strategy. If the object changes its behavior as its own state changes, it is State.Who picks thebehavior?Two stable cases:a plain ifThe caller:StrategyThe object itself:State
Strategy or State: who picks the next behavior?

In code

interface Discount { BigDecimal apply(BigDecimal total); }

class Checkout {
    private final Map<String, Discount> discounts;

    Checkout(Map<String, Discount> discounts) { this.discounts = discounts; }

    BigDecimal pay(BigDecimal total, String code) {
        Discount discount = discounts.getOrDefault(code, t -> t);   // unknown code: no discount
        return discount.apply(total);
    }
}

var checkout = new Checkout(Map.of(
    "PERCENT10", t -> t.multiply(new BigDecimal("0.90")),
    "FLAT15", t -> t.subtract(new BigDecimal("15")).max(BigDecimal.ZERO)));

checkout.pay(new BigDecimal("100"), "FLAT15");   // 85
checkout.pay(new BigDecimal("10"), "FLAT15");    // 0
Checkout depends on one interface
@Component("PERCENT10")
class PercentDiscount implements Discount {
    public BigDecimal apply(BigDecimal total) { return total.multiply(new BigDecimal("0.90")); }
}

@Component("FLAT15")
class FlatDiscount implements Discount {
    public BigDecimal apply(BigDecimal total) { return total.subtract(new BigDecimal("15")).max(BigDecimal.ZERO); }
}

@Service
class CheckoutService {
    private final Map<String, Discount> discounts;   // keys are bean names

    CheckoutService(Map<String, Discount> discounts) { this.discounts = discounts; }
}
In Spring, the map builds itself from the beans
Checkout and its discountsCheckout holds a map of Discount strategies and calls apply. PercentDiscount and FlatDiscount each implement the Discount interface, so a new discount needs no change in Checkout.«interface»Discount+apply(total)Checkout-Map discounts+pay(total, code)PercentDiscountFlatDiscount
Checkout and its discountsCheckout holds a map of Discount strategies and calls apply. PercentDiscount and FlatDiscount each implement the Discount interface, so a new discount needs no change in Checkout.«interface»Discount+apply(total)Checkout-Map discounts+pay(total, code)PercentDiscountFlatDiscount
Checkout uses the interface, and each discount implements it
interface ShippingCost { Money of(Parcel parcel); }

ShippingCost flat = parcel -> Money.of(5);
ShippingCost byWeight = parcel -> Money.of(2).times(parcel.kg());

Money cost = (parcel.kg() > 10 ? byWeight : flat).of(parcel);
With a functional interface, each strategy can be a lambda

Solve it

Strategy or State for an order’s status rules?

An order is NEW, PAID, SHIPPED or CANCELLED. cancel() refunds a paid order, works on a new one and fails once shipped; pay() only works on a new one. The code is a switch on status in every method. A teammate suggests Strategy.

  1. Ask who chooses. With Strategy the caller picks the algorithm and it stays. Here the order changes its own behavior as events happen.
  2. Pick State. Each status becomes an object that handles pay, ship and cancel and returns the next status.
  3. Put each rule in one place. “Cannot cancel once shipped” lives in Shipped.cancel() instead of in a switch in every method.
  4. Keep it small. An enum with one method per event is enough here; classes pay off when states carry data.
  5. Check. Test every event in every state: a transition that is not drawn below must throw.
enum Status {
    NEW       { Status pay() { return PAID; }   Status cancel() { return CANCELLED; } },
    PAID      { Status ship() { return SHIPPED; } Status cancel() { refund(); return CANCELLED; } },
    SHIPPED,
    CANCELLED;

    Status pay()    { throw new IllegalStateException(name() + " cannot be paid"); }
    Status ship()   { throw new IllegalStateException(name() + " cannot be shipped"); }
    Status cancel() { throw new IllegalStateException(name() + " cannot be cancelled"); }
    static void refund() { /* call the payment provider */ }
}

Status s = Status.NEW.pay().ship();   // SHIPPED
s.cancel();                           // IllegalStateException: SHIPPED cannot be cancelled
Each status decides what each event does next
The order states and the events that move between themA new order moves to paid on pay or to cancelled on cancel. A paid order moves to shipped on ship or to cancelled on cancel, with a refund. A shipped or cancelled order accepts no event.paycancelshipcancel, refundNEWPAIDCANCELLEDSHIPPED
The order states and the events that move between themA new order moves to paid on pay or to cancelled on cancel. A paid order moves to shipped on ship or to cancelled on cancel, with a refund. A shipped or cancelled order accepts no event.paycancelshipcancel, refundNEWPAIDCANCELLEDSHIPPED
The order states and the events that move between them

How to answer

  • Check first that the branches really are interchangeable behaviors.
  • One interface, one class or lambda per case, and a lookup instead of the branching.
  • The method now follows the Open/Closed Principle for new cases.
  • An enum with a method per constant suits a fixed, small set.

Common mistakes

  • Replacing every if with classes, even a two-branch check that never grows.
  • Moving the switch into a factory and calling the method free of branching without saying where the choice went.

Follow-up questions

What is the difference between Strategy and State?

They have the same class diagram but a different intent. In Strategy, the caller chooses a behavior, and the strategies do not know about each other. In State, the object moves itself between states as things happen, and each state often decides the next one. A discount is a Strategy; an order going from placed to paid to shipped is State.

  • Strategy: the choice comes from outside, and usually stays fixed for the call.
  • State: the transitions come from inside, so behavior changes over time.
  • States often know each other; strategies should not.

See it in the infographic: Swap the discount at runtime

Which SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation, Dependency inversion) principles does Strategy support?

Open/Closed: new behavior arrives as a new class, with no edit to the code that uses it. Dependency Inversion: the context depends on an interface rather than on concrete algorithms. Single Responsibility: each algorithm lives in one place. It also shows composition over inheritance, since behavior is held in a field and not inherited.

  • Open/Closed for adding cases.
  • Dependency Inversion through the Discount interface.
  • Composition lets you swap behavior at runtime, which a subclass cannot do.

See it in the infographic: Add a discount: if/else vs strategy map

Where does the JDK (Java Development Kit) use Strategy?

Comparator is the classic case: list.sort(comparator) keeps the sorting algorithm fixed and takes the ordering rule as an object. ThreadPoolExecutor takes a RejectedExecutionHandler for what to do when it is full. In Spring, AuthenticationProvider and PasswordEncoder are strategies chosen by configuration.

  • The caller supplies the behavior as an object or lambda.
  • The surrounding algorithm stays the same.
  • Passing a lambda is the shortest possible Strategy.

See it in the infographic: Swap the discount at runtime

How is Strategy different from Template Method?

Both vary part of an algorithm. Template Method uses inheritance: a base class fixes the steps and a subclass overrides some, so the choice is made at compile time. Strategy uses composition: the object holds a replaceable collaborator, so the choice can change at runtime and the same strategy can serve unrelated classes.

  • Template Method varies a step; Strategy replaces a whole algorithm.
  • A subclass is fixed once the object exists; a field can be swapped.
  • When in doubt, favor composition.

See it in the infographic: Swap the discount at runtime

Can an enum implement the Strategy pattern?

Yes, and it suits a fixed, small set of behaviors that do not need dependencies. Each constant supplies its own behavior, by overriding a method or holding a lambda, and valueOf gives you the lookup. Adding a case means editing the enum, so use interfaces and beans when others must add strategies, or when strategies need injection.

  • Constants are singletons, so they should hold no mutable state.
  • The compiler checks that every constant has the behavior.
  • An enum is closed to outside extension, unlike an interface.
enum DiscountType {
    PERCENT10(t -> t.multiply(new BigDecimal("0.90"))),
    NONE(t -> t);

    private final UnaryOperator<BigDecimal> rule;
    DiscountType(UnaryOperator<BigDecimal> rule) { this.rule = rule; }
    BigDecimal apply(BigDecimal total) { return rule.apply(total); }
}

Does Strategy need a class per algorithm in modern Java?

No. A one-method interface is a functional interface, so a lambda or method reference can be the strategy, as in names.sort(Comparator.comparing(String::length)). Write a class when the strategy holds state, needs its own dependencies or deserves its own test.

How do you pick the strategy with Spring?

Inject Map<String, Discount>. Spring fills it with every Discount bean, keyed by bean name, so a new @Component("FLAT15") is available with no other change. Injecting List<Discount> gives you all of them too, which suits strategies that each say whether they apply through a method such as supports(code).

What should happen with an unknown strategy key?

Decide on purpose. getOrDefault with a no-op strategy suits a discount code, where no discount is a valid outcome. For a payment type, throw IllegalArgumentException, because silently doing nothing would hide a bug. This no-op object is the Null Object pattern.

Check yourself

1. Checkout holds a Map of Discount strategies and calls apply(total). What must change in Checkout's code to add a new discount?
Show answers
  • Nothing in Checkout; the new strategy joins the map where it is built.: Correct. Checkout only knows the interface, so the new case arrives as data and a new class.
  • A new else-if branch: Incorrect. The branching is gone; a lookup replaced it.
  • A new method for that discount: Incorrect. Every discount is reached through the same apply call.
2. A "$15 off" strategy runs on a $10 order, and it stops at zero. What does Checkout charge?
Show answers
  • $0: Correct. The strategy applies max(0, total - 15), so it cannot go negative.
  • -$5: Incorrect. The strategy never returns less than zero.
  • $10: Incorrect. The discount still applies, and it takes the total down to zero.
3. An Order moves from placed to paid to shipped, and each stage decides what cancel() does and what stage comes next. Which pattern fits?
Show answers
  • State: Correct. The object moves between behaviors by itself as things happen.
  • Strategy: Incorrect. In Strategy the caller picks a behavior, and strategies do not hand over to each other.
  • Builder: Incorrect. Builder helps construct an object, not change its behavior later.