Separating validation from construction leaves callers responsible for remembering both steps, so invalid instances can slip through. validateThenCreate makes validation the creation boundary: it returns a new object only when its invariants pass, and otherwise returns errors explicitly. section 3.10 section 3.3.3
Keep the contract explicit:
- Use a private constructor so callers cannot bypass validation. section 3.10
- Run every relevant check and collect failures when the design requires reporting them together. section 3.10
- Return either the valid object or an error; commands commonly express this as Either<Error, T>. section 4.3.3
Accumulating Title errors
A Title factory checks that text is present and no longer than 500 characters. It runs both checks, returns both failures together when needed, and constructs the Title only when neither check fails. section 9.2.1
Listing 9.2 Title: Accumulating two field rules before deciding
@Getter
@Accessors(fluent = true)
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@RequiredArgsConstructor(access = AccessLevel.PRIVATE)
public class Title {
private static final int MAX_LENGTH = 500;
@EqualsAndHashCode.Include
private final String value;
public static Either<Error, Title>
validateThenCreate(final String title) {
final List<ValidationError> errors =
new ArrayList<>(); #A
Validations.mandatoryText(title, "title")
.peekLeft(errors::add); #B
Validations.maxLength(title, MAX_LENGTH,"title")
.peekLeft(errors::add);
return errors.isEmpty() #C
? Either.right(new Title(title))
: Either.left(new Error.ValidationErrors(
List.copyOf(errors)));
}
}
Inspect the Java implementation of a multi-rule factory that accumulates errors before constructing a Title. section 9.2.1
