Skip to content

Commit 8249fe9

Browse files
committed
refactor: Defer anyOf branch-error allocation to the failure path
1 parent 713f98f commit 8249fe9

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

src/main/java/com/retailsvc/http/validate/DefaultValidator.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,16 +527,20 @@ private Optional<ValidationError> checkAllOf(Object value, List<Schema> parts, S
527527
}
528528

529529
private Optional<ValidationError> checkAnyOf(Object value, List<Schema> options, String pointer) {
530-
List<ValidationError> failures = new ArrayList<>();
530+
List<ValidationError> failures = null;
531531
for (Schema o : options) {
532532
Optional<ValidationError> result = check(value, o, pointer);
533533
if (result.isEmpty()) {
534534
return OK;
535535
}
536+
if (failures == null) {
537+
failures = new ArrayList<>(options.size() - 1);
538+
}
536539
failures.add(result.get());
537540
}
541+
List<ValidationError> branches = failures != null ? failures : List.of();
538542
return Optional.of(
539-
new ValidationError(pointer, "anyOf", "did not match any anyOf branch", value, failures));
543+
new ValidationError(pointer, "anyOf", "did not match any anyOf branch", value, branches));
540544
}
541545

542546
private Optional<ValidationError> checkOneOf(Object value, List<Schema> options, String pointer) {
@@ -559,6 +563,8 @@ private Optional<ValidationError> checkOneOf(Object value, List<Schema> options,
559563
"oneOf",
560564
"matched " + matched + " of " + options.size() + " oneOf branches",
561565
value,
566+
// Ambiguous match (matched > 1): the non-matching branches' errors are noise — omit
567+
// them.
562568
matched == 0 ? failures : List.of()));
563569
}
564570

src/test/java/com/retailsvc/http/validate/DefaultValidatorDispatchTest.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,4 +273,12 @@ void anyOfNoMatchCapturesEachBranchError() {
273273
.containsExactly("minLength", "maxLength");
274274
});
275275
}
276+
277+
@Test
278+
void anyOfEmptyOptionsHasNoBranchErrors() {
279+
var schema = new AnyOfSchema(List.of(), Map.of());
280+
assertThatThrownBy(() -> v.validate("anything", schema, "/v"))
281+
.isInstanceOf(ValidationException.class)
282+
.satisfies(t -> assertThat(((ValidationException) t).error().branches()).isEmpty());
283+
}
276284
}

0 commit comments

Comments
 (0)