May 2018
Beginner to intermediate
290 pages
6h 43m
English
Aside from being convenient units of code, functions provide natural choke points where you can improve the reliability of your code by checking that the values passed to your function are what you expect. For example, if we had a function to publish a book and we wanted to make sure our book had a title before we did any publishing, we might write this:
| | ;; Publish a book using the (unseen) print-book |
| | ;; and ship-book functions. |
| | |
| | (defn publish-book [book] |
| | (when-not (contains? book :title) |
| | (throw (ex-info "Books must contain :title" {:book book}))) |
| | (print-book book) |
| | (ship-book book)) |
Happily, Clojure provides a shortcut for this sort of thing in the form of the :pre condition:
| | (defn publish-book ... |
Read now
Unlock full access