Video in progress
The number of discount rules grew from 5 to 60. Do you choose Strategy, Chain of Responsibility or a rules engine?
If only one rule runs at a time, Strategy. If the rules are applied one after another and affect each other, a chain or pipeline. If the business needs to change rules without a developer, a rules engine or data-driven rules.
📖 Answer
I start not from the pattern but from three questions.
Do the rules apply together? "10% for a new customer, then the promo code, then the discount must not exceed 30%" is sequential processing. A chain/pipeline fits:
public interface DiscountRule {
int order();
Money apply(PricingContext ctx, Money current);
}
Money total = rules.stream()
.sorted(Comparator.comparingInt(DiscountRule::order))
.reduce(base, (acc, r) -> r.apply(ctx, acc), (a, b) -> b);
The difference from a classic chain is that no rule stops the chain; each one only changes the value. If you need to stop it, you add a ctx.stop() flag.
Who changes the rules? If marketing launches a new promotion every week and each one needs a deploy, you become the bottleneck. Here you need to turn the rules into data: conditions and results in the database, and in the code a small interpreter that runs them. A full rules engine (like Drools) pays off only when the rules really have complex logic, and it comes with its own learning cost and is hard to debug.
Do you need to explain the result? A customer calls and asks "why didn't I get my discount?". Which rule gave how much, or why it was skipped, has to be recorded on every calculation. That is easy in a pipeline and harder in a rules engine.
With 60 rules there is one more risk: ordering. If two rules have the same order, the result is ambiguous. You should check for that at startup and fail.
Sign up to mark studied questions and save your progress.