Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Model pricing eligibility rules where a rule can be a single condition (such as minimum order total) or a group combining other rules with AND or OR. Write the interface and classes using the composite pattern.

We define interface Rule { boolean matches(Order order); }, write leaf rules such as MinTotalRule and CustomerTierRule that check one condition, and write AllOf and AnyOf, which hold a List<Rule> and combine their children's results with AND and OR. Because groups are rules too, clients call matches() the same way on a single condition or on a whole tree. In modern Java this fits a sealed interface with records, and if rules come from configuration we guard against cycles and very deep trees.

Why this question is asked

Eligibility rules, such as which customers get a discount or which orders qualify for free shipping, start simple and become nested quickly: gold customers, or anyone spending more than 100, but not for gift cards. Hard-coding each combination in if statements does not scale, especially when business people want to change rules without a release. The composite pattern is the natural model, and interviewers ask for it because it tests clean interface design and recursion in a few lines. In this answer, we will recap the composite pattern, write the interface and the leaf rules, write AllOf and AnyOf, build and evaluate a rule tree, rewrite it with a sealed interface and records, and add the guards needed when rules come from configuration.

1A Quick Recap of the Composite Pattern

The composite pattern lets us treat a single object and a group of objects the same way. There is one common interface. Leaves implement it directly; composites implement it by holding a list of children of that same interface and combining their results. Since a composite is itself an instance of the interface, it can be a child of another composite, so we can build trees of any depth.

For our rules, a leaf is one condition, such as the order total is at least 100. A composite is a group that combines other rules with AND or OR. A client that asks whether an order matches does not care which kind it holds.

2The Interface and the Leaf Rules

The interface has one method. The leaves each check one condition on the order.

Java
public interface Rule {
boolean matches(Order order);
}
public final class MinTotalRule implements Rule {
private final BigDecimal min;
public MinTotalRule(BigDecimal min) { this.min = min; }
public boolean matches(Order order) { return order.total().compareTo(min) >= 0; }
}
public final class CustomerTierRule implements Rule {
private final Set<Tier> tiers;
public CustomerTierRule(Set<Tier> tiers) { this.tiers = Set.copyOf(tiers); }
public boolean matches(Order order) { return tiers.contains(order.customer().tier()); }
}

We compare BigDecimal values with compareTo rather than equals, because equals also compares scale, so 100.0 and 100.00 would not be equal. The leaves are immutable, which makes a rule tree safe to share between threads and to cache.

3The Composites: AllOf and AnyOf

AllOf matches when every child matches; AnyOf matches when at least one does. Both hold a List<Rule> and delegate to their children.

Java
public final class AllOf implements Rule {
private final List<Rule> rules;
public AllOf(List<Rule> rules) { this.rules = List.copyOf(rules); }
public boolean matches(Order order) {
return rules.stream().allMatch(r -> r.matches(order)); // stops at the first false
}
}
public final class AnyOf implements Rule {
private final List<Rule> rules;
public AnyOf(List<Rule> rules) { this.rules = List.copyOf(rules); }
public boolean matches(Order order) {
return rules.stream().anyMatch(r -> r.matches(order)); // stops at the first true
}
}

Notice that allMatch and anyMatch short-circuit, just like && and ||, so cheap rules placed first save work on expensive ones. Also note the edge cases they inherit: allMatch on an empty list is true and anyMatch on an empty list is false, which matches logic but may surprise a business user, so a validator can reject empty groups. A NoneOf or Not rule fits the same shape when we need exclusions.

4Building and Evaluating a Rule Tree

Here is the rule gold or platinum customers, or anyone with an order total of at least 100, provided the order total is at least 20.

Java
Rule eligible = new AllOf(List.of(
new MinTotalRule(new BigDecimal("20")),
new AnyOf(List.of(
new CustomerTierRule(Set.of(Tier.GOLD, Tier.PLATINUM)),
new MinTotalRule(new BigDecimal("100"))))));
eligible.matches(order(Tier.SILVER, "150.00")); // true: total >= 20, and total >= 100
eligible.matches(order(Tier.GOLD, "35.00")); // true: total >= 20, and the tier matches
eligible.matches(order(Tier.SILVER, "35.00")); // false: neither branch of AnyOf matches
eligible.matches(order(Tier.GOLD, "10.00")); // false: fails the first rule, AnyOf is never evaluated
Step throughEvaluating the tree for a GOLD order of 35.00
  1. AllOf: check children in order
  2. MinTotalRule 20: 35.00 >= 20?
    YesContinue with AnyOfNoAllOf returns false
  3. AnyOf: check children in order
  4. CustomerTierRule GOLD or PLATINUM?
    YesAnyOf returns true, so AllOf returns trueNoTry MinTotalRule 100

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

Short-circuiting means the MinTotalRule 100 leaf is never evaluated for this order.

The client code only ever calls eligible.matches(order). Whether eligible is a single condition or a tree of twenty rules, the call is the same, and that uniformity is what the pattern gives us.

5The Same Model With a Sealed Interface and Records

Since Java 17, a sealed interface can list exactly which types implement it, and records give us immutable classes in one line each. That makes the rule model shorter, and the compiler knows every kind of rule, which helps with operations beyond matching, such as describing a rule to a business user.

Java
public sealed interface Rule permits MinTotal, CustomerTier, AllOf, AnyOf {
boolean matches(Order order);
}
public record MinTotal(BigDecimal min) implements Rule {
public boolean matches(Order o) { return o.total().compareTo(min) >= 0; }
}
public record CustomerTier(Set<Tier> tiers) implements Rule {
public CustomerTier { tiers = Set.copyOf(tiers); }
public boolean matches(Order o) { return tiers.contains(o.customer().tier()); }
}
public record AllOf(List<Rule> rules) implements Rule {
public AllOf { rules = List.copyOf(rules); }
public boolean matches(Order o) { return rules.stream().allMatch(r -> r.matches(o)); }
}
public record AnyOf(List<Rule> rules) implements Rule {
public AnyOf { rules = List.copyOf(rules); }
public boolean matches(Order o) { return rules.stream().anyMatch(r -> r.matches(o)); }
}
static String describe(Rule r) {
return switch (r) { // exhaustive: no default needed
case MinTotal m -> "total >= " + m.min();
case CustomerTier t -> "tier in " + t.tiers();
case AllOf a -> a.rules().stream().map(Main::describe).collect(Collectors.joining(" AND ", "(", ")"));
case AnyOf a -> a.rules().stream().map(Main::describe).collect(Collectors.joining(" OR ", "(", ")"));
};
}
// describe(eligible) -> (total >= 20 AND (tier in [GOLD, PLATINUM] OR total >= 100))

Records also give us equals() and hashCode() for free, so two identical rule trees are equal, which is handy for tests and caching.

6Guarding Rules That Come From Configuration

If rules are loaded from JSON or a database, edited by people, two new risks appear. A cycle can occur when groups reference other groups by name, for example group A includes group B and B includes A; building the tree would loop forever, or matches() would overflow the stack. And a very deep or very large tree, by mistake or by a malicious edit, can make every evaluation slow.

So the loader validates while it builds: it keeps the set of group names currently being resolved and rejects a name that is already in the set, which detects cycles, and it rejects trees deeper than a limit, say 10 levels, or larger than, say, 500 nodes. Because our records are immutable and built bottom-up, a tree that passes the loader cannot gain a cycle later.

7Follow-up questions

Why not just write the rules as Predicate<Order> and combine them with and() and or()?

That works well for rules defined in code, and Predicate.and and Predicate.or are themselves a composite. The explicit Rule types win when rules must be stored, loaded from configuration, described to users or validated, because a lambda cannot be inspected or serialised, while a record tree can.

How would you explain why an order did not match?

Add a method that returns a result with the reason instead of a boolean, such as an Evaluation with matched and a list of failed leaves. Composites collect their children's results. With the sealed version, this can also be a separate function using a switch, without changing the record types.

Where does the composite pattern appear in the JDK or Spring?

In Swing and AWT, a Container is a Component that holds other Components. In Spring Security, authorization managers can be combined with AuthorizationManagers.allOf and anyOf, check your version, which is exactly this pattern.

8Conclusion

In this answer, we modelled pricing eligibility with the composite pattern. The Rule interface has one method, matches(order); leaf rules like MinTotalRule and CustomerTierRule check one condition, and AllOf and AnyOf hold a List<Rule> and combine results with short-circuiting AND and OR. Clients treat single rules and groups the same way. A sealed interface with records gives the same model more concisely, with exhaustive switches for operations like describing a rule, and when rules come from configuration, the loader guards against cycles and very deep trees.

What to say in the interviewAbout 70 seconds aloud

Open with

I'd start with a single-method interface, Rule with boolean matches(Order order). Leaf rules implement it directly: MinTotalRule holds a BigDecimal and compares the order total with compareTo, not equals, because equals also compares scale; CustomerTierRule holds a set of tiers and checks the customer's tier.

Then, if they want more

Then the composites: AllOf and AnyOf each hold a List<Rule>, copied with List.copyOf so they're immutable, and matches uses allMatch or anyMatch over the children, which short-circuit just like && and ||.

Because groups are rules too, I can nest them to any depth, and the client always just calls matches, whether it holds one condition or a tree of twenty. In modern Java I'd write it as a sealed interface Rule permitting four records.

That's shorter, immutable, gives equals for free, and lets me write other operations, like a human-readable description, as an exhaustive switch over the rule types without a default branch.

If the rules come from configuration, I'd validate in the loader: track the group names being resolved to reject cycles, and cap depth and size, so a bad edit can't loop forever or make every evaluation slow.

About this answer

Last updated
12 November 2026
Versions it names
Java 17
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 "Model pricing eligibility rules where a rule can be a single condition (such as minimum...": https://scrivio-interview-library.netlify.app/java/structural-patterns/d6ebf73d80/