liveBook · Manning

Factory

As explained in Clean Applications with Hexagonal Architecture

A construction abstraction that creates objects while encapsulating their creation logic.

When callers construct objects first and validate them later, invalid state can escape. Moving checks into handlers avoids that window but spreads business rules across creation paths. A factory encapsulates construction so callers receive either a valid object or an error. section 3.3.1 section 3.3

For a simple entity, keep the constructor private and put a factory method on the entity itself. The method validates every invariant before invoking the constructor. This keeps business rules in the framework-independent domain rather than relying on each handler to remember them. section 3.10 section 3.3.1

A validateThenCreate method can use Vavr’s Validation to combine field checks. If they all pass, applying the constructor creates the entity; otherwise, the result contains the validation errors. Unlike Either, Validation can collect failures from multiple checks. section 3.3.2

Listing 3.4 Example of invalid fields returned as errors to the user
final Validation<Seq<DomainError>, Article> result =
  Article.validateThenCreate(
    new ArticleId(UUID.randomUUID()),
    null,           // invalid — title is null
    new Content(""), // invalid — content is blank
    new AuthorId(UUID.randomUUID()));
 
// result is Validation.invalid containing TWO errors:
// [DomainError("Title must not be blank"),
//    DomainError("Content must not be blank")]

A null title and blank content produce two errors in one creation attempt. section 3.3.2

Use a standalone factory when construction needs injected dependencies, such as an identity generator or an output port. It coordinates those concerns, then delegates to the entity’s validation factory; it does not make the entity constructor public. Keep the standalone factory focused on creation rather than unrelated business logic. section 3.6

Listing 3.14 Using factories for complex construction of entities
public class ArticleFactory { #A
  private final ArticleIdGenerator idGenerator;
 
  public ArticleFactory(final ArticleIdGenerator idGenerator) {
    this.idGenerator = idGenerator; #B
  }
 
  public Validation<Seq<DomainError>, Article> create( #C
    final Title title, final Content content, final AuthorId authorId) {
    final ArticleId id = this.idGenerator.next(); #D
    return Article.validateThenCreate(id, title, content, authorId);
  } #E
}

ArticleFactory generates an ID and delegates invariant checks to Article.validateThenCreate. section 3.6

The same private-constructor discipline can protect commands at the application boundary. A valid command does not guarantee a successful use case: an article may still be missing or publication may be forbidden. Test successful creation and field mapping as well as rejection of invalid inputs. section 4.1.2 section 8.3.1 section 3.3.2

How Clean Applications with Hexagonal Architecture covers it

How deep it goes
Works through private constructors, combined validation, error returns, and standalone factories that delegate to entity factories.
Examples
Uses Article creation with invalid title and content, an ID-generating ArticleFactory, and PublishArticleCommand creation tests.
What it assumes
Introduces Vavr Validation without requiring functional programming terminology.
What you can do after
Build validated factory methods and standalone coordinating factories for domain objects.
How it connects
Connects factories to domain invariants, value objects, dependency injection, output ports, and boundary validation.

Also explained in

Compare how 13 books explain factory →

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.