liveBook · Manning

Precondition

As explained in Clojure: The Essential Reference

A precondition is a Boolean assertion that must hold before a function body executes.

A precondition checks an input before a Clojure function body runs. Put Boolean assertions in a `:pre` vector immediately after the argument vector in `defn`. If an assertion fails, the call raises an `AssertionError` instead of evaluating the body. section 2.1.1

Check an item before saving it

`(defn save! [item] {:pre [(map? item) (integer? (:mult item)) (#{:double :triple} (:width item))]} (assoc item :id (* (:mult item) 2)))` `(save! {:mult "4" :width :single})` fails the input checks. `{:mult 5 :width :double}` passes and receives `:id 10`. section 2.1.1

A related `:post` vector checks the result after the body runs; its assertions can refer to the return value as `%`. Use `:pre` for required inputs and `:post` for required results. section 2.1.1

How Clojure: The Essential Reference covers it

How deep it goes
Defines placement and failure behavior, then demonstrates input checks; does not explore assertion internals.
Examples
Checks a `save!` item’s map shape, integer multiplier, and permitted width; shows failures for invalid input.
What you can do after
Apply it via Clojure `defn` to reject inputs that violate a function’s requirements before its body runs.
How it connects
Connects preconditions to `defn`, metadata maps, postconditions, and `clojure.test` assertions.

Also explained in

Compare how 8 books explain precondition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.