liveBook · Manning

Precondition

As explained in Unit Testing Principles, Practices, and Patterns

A precondition is a condition that must hold before an operation can execute while preserving an object's valid state.

A precondition is a safeguard requiring a condition to hold before an operation proceeds. It protects an object's valid state by failing fast when code would otherwise create invalid data. section 7.3 section 7.2

The condition can enforce a domain invariant, such as preventing a company's employee count from becoming negative. Violations usually indicate bugs rather than ordinary business cases. section 7.3

Use preconditions selectively when deciding what deserves unit-test coverage:

  • Test safeguards with domain significance because they express requirements that must remain true. section 7.3
  • Avoid spending test effort on incidental checks, such as requiring a factory input array to contain three elements. section 7.3
  • Keep required conditions at construction boundaries when they maintain encapsulation, including private constructors used by persistence mechanisms. section 11.1

Preventing an invalid employee count

Company.ChangeNumberOfEmployees requires NumberOfEmployees + delta >= 0 before updating the property. A negative result throws immediately instead of allowing invalid state to spread or reach the database. section 7.3

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines safeguards, explains fail-fast preservation, and demonstrates implementation and testing trade-offs.
Examples
Uses employee-count validation, UserFactory input-length validation, and an Inquiry approval-time invariant.
What it assumes
Assumes familiarity with object-oriented classes, invariants, unit tests, and domain-model refactoring.
What you can do after
Evaluate preconditions for domain significance and place safeguards where invalid state must fail immediately.
How it connects
Connects preconditions to object invariants, unit testing, fail-fast behavior, domain significance, and domain models.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.