Function Specs

So far we’ve been treating clojure.spec as a general-purpose library for ensuring that our data looks the way it should. And so it is. But think about how useful it would be during development to have a way to automatically do some spec matching at critical points in your code. For example, wouldn’t it be great if you could write a spec for the arguments of a function and have that spec checked each time the function is called?

We could do this by taking advantage of function pre and post conditions:

 ;; Register a handy spec: An inventory is a collection of books.
 
 (s/def :inventory.core/inventory
  (s/coll-of ::book))
 
 
 (​defn​ find-by-title
  [title inventory]
  {:pre [(s/valid? ::title title)
  (s/valid? ::inventory ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.