liveBook · Manning

Validatethencreate

As explained in Clean Applications with Hexagonal Architecture

A construction pattern that validates all required constraints before creating an object and returns validation errors instead of an invalid object.

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

How Clean Applications with Hexagonal Architecture covers it

How deep it goes
Defines private construction and explicit errors, contrasts exception-based and split validation, and shows how to accumulate failures.
Examples
Uses Article commands and a Title value object whose presence and length checks can fail together.
What you can do after
Build factories that construct objects only after checks pass and return validation failures explicitly.
How it connects
Connects the always-valid domain model, value objects, commands, Either-based errors, and architectural tests.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clean Applications with Hexagonal Architecture. The section links point to the parts of the book it draws on.