Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build robust data apis in clojure?

I find that my clojure apps get structurally coupled very rapidly due to the lack of a data API. I have maps with keys that have names which, if mistyped, because exceptions to be thrown or errors. I also notice that it's easy to make mistakes when destructuring a list (for example maybe you destructure the wrong part of the list).

Coming from the Java world, normally I use my IDE to help me to get the "right" data out of minimal, unordered data objects. But clojure map passing seems to be the opposite paradigm from this.

How do clojurians code defensively in the absence of a type system or ide code completion?

like image 958
jayunit100 Avatar asked Oct 07 '11 05:10

jayunit100


1 Answers

Write validators functions for your "schemas" (keys but also type of values etc.) then use thm inside pre- and post- conditions in your code -- since their syntax is little known here is a quick refresher:

(defn foo [x y] ; works with fn too
  {:pre [(number? x) (number? y)]
   :post [(number? %) (pos? %)]}
  (+ (* x x) (* y y)))

They rely on assert and hence can be disabled. (doc assert) for more details.

like image 56
cgrand Avatar answered Oct 23 '22 23:10

cgrand