Validate Builders On Build

RUST-VALIDATE-BUILDERS-ON-BUILD

Summary

Validate cross-field builder invariants in build where partial configuration becomes a usable value. Keep build infallible only when defaults and setters make invalid states impossible.

Rule

Builder build methods should validate cross-field invariants and return errors when construction can fail.

Why

Builders spread configuration across multiple calls. Cross-field rules often become visible only when all fields are known, so validation belongs at the point that turns partial configuration into a usable value.

The Pragmatic Rust Guidelines recommend builders for complex construction because they let callers name optional inputs and keep initialization readable. That benefit disappears if build returns a value whose cross-field invariants were never checked.

Helps

  • Helps keep partially configured builders flexible while keeping constructed values valid.

Limits

Use infallible build when defaults and setters make invalid states impossible. Prefer typed state builders only when the invariant is important enough to justify extra API complexity. Keep setter methods cheap and defer validation only when a field cannot be judged independently.

Agent Instruction

Validate Rust builder cross-field invariants in `build` and return an error for fallible
construction.

Mechanisms

Supported by constructor tests, invalid-combination tests, and examples that show fallible builder construction.

References