Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

This method grows every time marketing adds a customer type:

Java
BigDecimal discount(Customer c, BigDecimal total) {
if (c.type() == GOLD) return total.multiply(new BigDecimal("0.10"));
else if (c.type() == SILVER) ...
}

Refactor it with the strategy pattern using modern Java.

We replace the if-else chain with the strategy pattern: a functional interface DiscountPolicy with one method, discount(BigDecimal total), and one policy per customer type, held as a field on the CustomerType enum or in an EnumMap. Simple policies are lambdas, complex ones are classes, and the calling code just looks up the policy and calls it, with no conditionals. Adding a customer type then means adding one constant with its policy, not editing a growing method.

Why this question is asked

Methods like this one start with two branches and are perfectly fine. The trouble comes later, when every new customer type means opening the same method, adding another branch, and hoping nothing else changes by accident. Interviewers use this example because it tests whether we can spot the strategy hiding inside a conditional and whether we know the modern Java way to write it, which is far shorter than the textbook version with one class per strategy. In this answer, we will look at what is wrong with the original method, introduce the strategy pattern with a functional interface, attach policies to the enum, see when a policy deserves its own class, and write the tests.

1What Is Wrong With the Growing Method

Here is the method as it stands. Each customer type has its own way of computing a discount, and all of them live in one place.

Java
BigDecimal discount(Customer c, BigDecimal total) {
if (c.type() == GOLD) {
return total.multiply(new BigDecimal("0.10"));
} else if (c.type() == SILVER) {
return total.multiply(new BigDecimal("0.05"));
} else if (c.type() == STUDENT) {
return total.compareTo(new BigDecimal("50")) >= 0 ? new BigDecimal("5.00") : BigDecimal.ZERO;
}
return BigDecimal.ZERO;
}
discount(goldCustomer, new BigDecimal("200.00")); // 20.0000

Notice three problems. The method changes every time marketing adds a type, so it is never finished, and every change risks breaking the other branches. The rules for one customer type cannot be tested without going through the whole chain. And if someone adds a new enum constant and forgets this method, the customer silently gets zero discount, because the fallback hides the mistake. Notice also that 200.00 times 0.10 gives 20.0000, because BigDecimal multiplication adds the scales; we will fix that while refactoring.

2A Quick Recap of the Strategy Pattern

The strategy pattern takes a family of interchangeable algorithms, gives them a common interface, and lets the caller pick one at runtime. The caller depends only on the interface; it never needs to know which algorithm it holds. Each variation, a discount rule here, lives in its own place.

The best-known JDK strategy is Comparator. List.sort does not know how to order our objects; we pass it a Comparator, and the sort algorithm calls it. Comparator.comparing(Person::name) and Comparator.reverseOrder() are different strategies for the same sort. In modern Java, a strategy with a single method is a functional interface, so a lambda or method reference is a complete implementation.

Java
@FunctionalInterface
public interface DiscountPolicy {
BigDecimal discount(BigDecimal total);
static DiscountPolicy percent(String rate) {
BigDecimal r = new BigDecimal(rate);
return total -> total.multiply(r).setScale(2, RoundingMode.HALF_UP);
}
DiscountPolicy NONE = total -> BigDecimal.ZERO;
}

The two helpers keep common rules readable. percent("0.10") builds a lambda that multiplies and rounds to cents, which fixes the scale problem in one place for every percentage rule.

3Attaching a Policy to Each Customer Type

Because customer types are an enum, the simplest home for the policy is the enum itself. Each constant passes its policy to the enum constructor. The compiler then forces every new constant to provide one, which removes the silent zero-discount bug.

Java
public enum CustomerType {
GOLD(DiscountPolicy.percent("0.10")),
SILVER(DiscountPolicy.percent("0.05")),
STUDENT(total -> total.compareTo(new BigDecimal("50")) >= 0 ? new BigDecimal("5.00") : BigDecimal.ZERO),
REGULAR(DiscountPolicy.NONE);
private final DiscountPolicy policy;
CustomerType(DiscountPolicy policy) { this.policy = policy; }
public DiscountPolicy policy() { return policy; }
}
BigDecimal discount(Customer c, BigDecimal total) {
return c.type().policy().discount(total); // no conditionals left
}
discount(goldCustomer, new BigDecimal("200.00")); // 20.00
discount(studentCustomer, new BigDecimal("40.00")); // 0
discount(studentCustomer, new BigDecimal("80.00")); // 5.00
Step throughHow a discount is computed after the refactoring
  1. discount(customer, total)Caller code, unchanged by new types
  2. Look up customer.type().policy()Enum field or EnumMap entry
  3. Call policy.discount(total)Lambda or class, chosen per type
  4. Return the amount, rounded to centsOne rounding rule in percent()

4 steps in order. Play them, or step through them one at a time.

The calling method is now one line. It looks up the policy for the customer's type and calls it. Adding a PLATINUM type is a one-line change in the enum, and the discount method never changes again.

Sometimes the enum is not ours to edit, or different parts of the system price differently for the same type. Then an EnumMap<CustomerType, DiscountPolicy> built in one place does the same job. EnumMap is backed by an array indexed by ordinal, so lookups are fast. To keep the compiler's safety net, we check at startup that every constant has an entry.

4When a Policy Deserves Its Own Class

Lambdas are right for one-line rules. When a rule grows, for example a loyalty discount that depends on the customer's spend over the last year and a cap per order, a lambda becomes hard to read and impossible to give dependencies. Then we write a class that implements the same interface. Callers do not notice the difference.

Java
public final class LoyaltyPolicy implements DiscountPolicy {
private final BigDecimal cap;
public LoyaltyPolicy(BigDecimal cap) { this.cap = cap; }
@Override public BigDecimal discount(BigDecimal total) {
BigDecimal d = total.multiply(new BigDecimal("0.15")).setScale(2, RoundingMode.HALF_UP);
return d.min(cap); // never more than the cap
}
}
new LoyaltyPolicy(new BigDecimal("30.00")).discount(new BigDecimal("500.00")); // 30.00

If a policy needs data that depends on the customer and not only on the total, the interface should take that data too, for example discount(Customer c, BigDecimal total). It is better to widen the interface once than to let one policy reach out to global state.

5Testing the Policies

Each policy can now be tested on its own, with plain values and no customer objects. A parameterised JUnit test covers the table of examples, and one extra test makes sure every enum constant has a policy, which matters for the EnumMap variant.

Java
@ParameterizedTest
@CsvSource({"GOLD,200.00,20.00", "SILVER,200.00,10.00", "STUDENT,40.00,0", "STUDENT,80.00,5.00"})
void discountPerType(CustomerType type, BigDecimal total, BigDecimal expected) {
assertEquals(0, expected.compareTo(type.policy().discount(total))); // compareTo ignores scale
}

We compare with compareTo rather than equals because BigDecimal.equals also compares the scale, so 0 and 0.00 would not be equal.

6Follow-up questions

Why not put an abstract discount method on the enum and override it in each constant?

That also works and is another form of the same pattern: constant-specific class bodies. Passing a lambda to the constructor is usually shorter and lets us reuse helpers like percent(). Constant bodies are fine when each rule is a few lines and the enum is ours.

Can you name another strategy in the JDK besides Comparator?

Yes. ThreadPoolExecutor takes a RejectedExecutionHandler that decides what happens when the queue is full, with strategies like AbortPolicy and CallerRunsPolicy. Comparator remains the most familiar one, because every sort call passes a strategy.

Is a switch expression on a sealed type a better answer?

It is a good answer when the set of cases is fixed and we want the compiler to check that every case is handled, and the rule belongs with the caller. Strategy is better when new types are added often and each rule should live with its type. Both remove the open-ended if-else chain.

7Conclusion

In this answer, we saw that the growing if-else chain mixes every discount rule in one method and hides missing cases. We defined a functional interface DiscountPolicy, gave each customer type a policy through the enum constructor or an EnumMap, wrote simple rules as lambdas and complex ones as classes, and reduced the caller to a lookup and a call. Comparator is the familiar JDK example of the same strategy pattern.

What to say in the interviewAbout 100 seconds aloud

Open with

The problem with this method is that every new customer type means editing the same chain, and a forgotten branch silently gives zero discount. I would refactor it with the strategy pattern.

Then, if they want more

First I define a functional interface, DiscountPolicy, with one method that takes the total and returns the discount. Because it is functional, simple rules can be lambdas, and I would add a small helper like percent that multiplies and rounds to two decimal places, which also fixes the BigDecimal scale in one place.

Then I attach a policy to each customer type. Since the type is an enum, the cleanest way is a constructor argument, so GOLD is created with percent ten, SILVER with percent five, and so on. The compiler then forces every new constant to supply a policy.

If the enum is not mine, or pricing differs by context, I would use an EnumMap from type to policy and check at startup that every constant is mapped. The discount method becomes one line: look up the customer's policy and call it, with no conditionals.

When a rule gets complicated, like a loyalty discount with a cap, I write a class that implements the same interface, and callers do not notice. Each policy can then be tested on its own with a parameterised test.

Comparator is the everyday JDK example of this pattern: the sort algorithm stays the same and we pass in the ordering strategy.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This method grows every time marketing adds a customer type:": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/f90ecf691d/