liveBook · Manning

Precondition

As explained in Software Design for Python Programmers

A precondition is a state or event that must hold or have occurred before a use case can begin.

A precondition is a Boolean condition that must be true before a use case, method, or function begins. In a use case, it records what must already hold or have happened; in programming by contract, it defines what the caller must establish before calling. section 3.6.2 section 6.3.2

Use a precondition to make responsibilities and expected behavior explicit:

  • Have the caller check the condition before making the call. section 6.3.2
  • Document the condition clearly, and provide a public way to check it when it belongs to a class method. section 6.3.2
  • Treat a satisfied precondition as a promise that the function will behave correctly; an unsatisfied one releases that guarantee. section 6.3.2 section 6.4

Circular buffer

For a CircularBuffer, add() requires self._count < self._capacity, so the caller must avoid adding when the buffer is full. remove() requires self._count > 0, so the caller must avoid removing from an empty buffer. Once the relevant condition holds, add() must insert at the tail and advance it, while remove() must remove from the head, advance it, and return the value. section 6.3.2

Preconditions form one part of a programming-by-contract design alongside postconditions and class invariants. Python has no native contract support, but these ideas can still be implemented with existing language features, especially for critical classes. section 6.3

How Software Design for Python Programmers covers it

How deep it goes
Explains Boolean conditions, caller responsibility, documentation, guarantees, and CircularBuffer predicates, but not formal verification.
Examples
Demonstrates full and empty CircularBuffer checks through add() and remove() operations.
What it assumes
Assumes familiarity with functions and classes while teaching contract responsibilities through a concrete buffer example.
What you can do after
Apply it by documenting callable requirements and checking them before operations that depend on valid starting states.
How it connects
Connects preconditions to use cases, programming by contract, postconditions, and class invariants.

Also explained in

Compare how 8 books explain precondition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.