Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

Design a validation component where rules can be combined, for example Rule<Order> = notEmpty.and(maxItems(50)).and(validAddress), and the result lists all failures, not only the first. How would you model it?

I would model a rule as interface Rule<T> { List<String> check(T value); } with a default and(Rule<T> other) that runs both rules and concatenates their failure lists instead of short-circuiting, so the combined rule reports every failure. Static factory methods such as maxItems(n) build rules, and rules stay pure so they can be reused and tested on their own. Composing plain Predicates would not work here, because a Predicate only answers true or false and loses the reasons.

Why this question is asked

Validation is a place where composition pays off quickly: an order, a sign-up form or an import row each has many small rules, and different flows need different combinations. Users also expect to see every problem at once, not to fix one error, resubmit and discover the next. Interviewers ask this design question to see whether we can shape a small functional API that composes like Predicate but carries more information. In this answer, we will see why predicates are not enough, design the Rule interface, build rules with factories, use the combined rule, discuss purity, and handle rules that depend on each other.

1Why Predicate Composition Is Not Enough

Java already has Predicate with and, so it is tempting to write notEmpty.and(maxItems).and(validAddress) with predicates. The problem is the result type.

Java
Predicate<Order> notEmpty = o -> !o.items().isEmpty();
Predicate<Order> validAddress = o -> o.shippingAddress() != null;
notEmpty.and(validAddress).test(new Order(List.of(), null)); // false: but why?

The answer is a single false. We cannot tell the user which rules failed, and because Predicate.and short-circuits, the second rule is not even evaluated once the first fails. For validation we need two different things: a result that carries the reasons, and a combination that runs every rule.

2Designing the Rule Interface

A rule takes a value and returns the list of failures, empty when the value is valid. Combining two rules means running both and joining their lists.

Java
@FunctionalInterface
public interface Rule<T> {
List<String> check(T value); // empty list means valid
default Rule<T> and(Rule<T> other) {
return value -> {
List<String> failures = new ArrayList<>(this.check(value));
failures.addAll(other.check(value)); // always runs: no short-circuit
return List.copyOf(failures);
};
}
static <T> Rule<T> of(Predicate<T> test, String message) {
return value -> test.test(value) ? List.of() : List.of(message);
}
}

Notice three choices. Rule is a functional interface, so a lambda can be a rule. and returns a new Rule, so combinations are themselves rules and can be combined further. And of adapts a Predicate plus a message into a Rule, so simple checks stay one-liners while the result keeps its reason. Inside the lambda in and, this refers to the rule on which and was called, which is how the combined rule reaches both sides.

3Building Rules With Static Factories

Named factories turn configuration into readable rules. A factory such as maxItems(n) takes a parameter and returns a rule that has captured it.

Java
public final class OrderRules {
public static final Rule<Order> notEmpty =
Rule.of(o -> !o.items().isEmpty(), "order has no items");
public static Rule<Order> maxItems(int n) {
return Rule.of(o -> o.items().size() <= n, "order has more than " + n + " items");
}
public static final Rule<Order> validAddress = o ->
o.shippingAddress() == null ? List.of("shipping address is missing")
: AddressRules.complete.check(o.shippingAddress());
}
Rule<Order> checkout = notEmpty.and(maxItems(50)).and(validAddress);
checkout.check(new Order(List.of(), null));
// [order has no items, shipping address is missing]
checkout.check(new Order(List.of(book), new Address("1 Main St", "Leeds", "")));
// [postcode is missing]
checkout.check(new Order(List.of(book), fullAddress));
// []
Step throughcheckout.check(order) for an empty order with no address
  1. notEmptyfails: "order has no items"
  2. maxItems(50)passes: no failure added
  3. validAddressfails: "shipping address is missing"
  4. Concatenate the liststwo failures returned together

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

The first check shows the point of the design: both failures are reported together. validAddress also shows that a rule can delegate to rules for another type, here the address, so rule sets grow by reuse rather than copy and paste.

4Keeping Rules Pure

Every rule above is a pure function: its result depends only on the value passed in, and it changes nothing. That is what makes the design work. Pure rules can be shared as constants, combined in any order with the same result, run on any thread, and tested with a single line each, such as assertEquals(List.of("order has no items"), notEmpty.check(emptyOrder)).

Some checks seem to need outside data, such as "the product must be in stock". Rather than calling a database inside the rule, we pass the data in: a factory inStock(Set<Sku> available) returns a rule that checks against the set the caller loaded. The rule stays pure, and the loading happens once, outside, where it belongs.

5When One Rule Depends on Another

Running every rule has one catch: a later rule may only make sense if an earlier one passed. Checking the postcode format when the address is missing would either fail with a NullPointerException or add a meaningless second message. validAddress above handles this inside one rule, and for a reusable answer we can add a second combinator that short-circuits on purpose.

Java
default Rule<T> andThenIfValid(Rule<T> next) {
return value -> {
List<String> first = this.check(value);
return first.isEmpty() ? next.check(value) : first; // only run next if this passed
};
}
Rule<Address> complete = present.andThenIfValid(postcodeFormat.and(cityKnown));

So the API offers two ways to combine: and to collect independent failures, and andThenIfValid for dependent checks. Choosing between them is a visible decision in the code, rather than a hidden assumption inside a rule.

6Growing the Design

For a real system I would replace the plain String with a small record, such as Violation(String field, String code, String message), so a user interface can highlight the right field and translate the message, and an API can return machine-readable codes. I would also add Rule.all(rules...) to combine a list, and a helper that lifts a rule for a part into a rule for the whole, such as on(Order::shippingAddress, AddressRules.complete).

Jakarta Bean Validation also collects all violations and suits field-level constraints declared with annotations. A composable Rule type fits better when rules are cross-field, depend on context, or are assembled differently per flow, and the two can coexist.

7Follow-up questions

Why return an immutable list from and?

Because rule results may be shared or combined further, and an immutable list prevents a caller from adding to another rule's result by accident. List.copyOf also makes the result safe to cache or pass across threads.

How would you test the combination itself?

With two stub rules that always fail with known messages: a.and(b).check(x) should return both messages in order, and a passing rule combined with a failing one should return only the failing message. These tests check the combinator once, so individual rules need only their own tests.

Could this be done with Either or a validation type from a library?

Yes; functional libraries offer accumulating validation types for exactly this. The small interface above gives the same behaviour with plain Java types that every developer can read, which is usually the better trade in a shared codebase.

8Conclusion

In this answer, we saw that predicate composition loses the reasons and stops at the first failure, so validation needs its own type. Rule<T> returns a list of failures, its default and method runs both rules and concatenates their lists, static factories such as maxItems(n) build readable rules, and keeping rules pure makes them reusable and trivial to test. A second, short-circuiting combinator handles rules that depend on others, and violation records with field and code make the design ready for real user interfaces and APIs.

What to say in the interviewAbout 90 seconds aloud

Open with

Predicates alone won't work, because Predicate.and gives a single true or false and short-circuits, so we lose both the reasons and every failure after the first. So I'd define a functional interface Rule of T with one method, check, that returns a List of String failures, empty when the value is valid.

Then, if they want more

The key is a default method and that takes another rule and returns a lambda that runs this.check and other.check and concatenates both lists, without short-circuiting, so the combined rule reports everything. A static helper Rule.of takes a Predicate and a message, so simple checks stay one-liners.

Then static factories build named rules, like maxItems of n, which captures n and returns a rule. So notEmpty.and(maxItems(50)).and(validAddress) on an empty order with no address returns both messages at once.

I'd keep every rule pure: the result depends only on the input, and if a rule needs outside data like stock levels, the factory takes that data as an argument. That makes rules shareable constants, thread-safe and testable in one line each.

For dependent checks, like validating a postcode only when an address exists, I'd add a second combinator that only runs the next rule if the first passed. In production I'd replace the strings with a Violation record carrying field, code and message.

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 documentation below. 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 "Design a validation component where rules can be combined, for example Rule<Order> =...": https://scrivio-interview-library.netlify.app/java/functional-design/b6c87e8b6a/