November 10, 2016

clojure.spec

Specification is much more powerful than static typing plus you also get validation, instrumentation and generative testing – clojure.spec (by Rich Hickey)

Example (spec forĀ URIs):

(ns example.specs
  (:require #?(:clj  [clojure.spec :as s]
               :cljs [cljs.spec :as s])
            [clojure.string :as str]))
;; URI spec.
(def uri?
  (s/and string? #?(:clj #(try (do (java.net.URI. %) true) (catch Exception e false))
                    :cljs #(= (str/replace (js/encodeURI %) "%25" "%") %))))
;; e.g. Call as follows:
(s/valid? uri? "https://www.google.nl/url?q=https://www.reddit.com/r/Clojure/comments/4kutl7/clojurespec_guide/&sa=U&ved=0ahUKEwic2v3-r6DQAhVBGsAKHcrVCZMQFggUMAA&usg=AFQjCNHs0DmF1uNIw9BYUK7pqpgp5HEbow")

Videos:

Tags: Software Computer Testing Clojure ClojureScript Functional