Hierarchical Specifications

Defining specifications for data that is hierarchical or nested in nature.

  1. (ns practicalli.clojure
  2. (:require [clojure.spec.alpha :as spec]))

Example hierarchical data

  1. {:top-level-key {:netsted-key "value"}}

Individual specifications

  1. (spec/def ::first-name string?)
  1. (spec/def ::last-name string?)
  1. (spec/def ::residential-address string?)

Composite Specification

keys function combines specifications to form a composite specification in the form of a Clojure hash-map.

  1. (spec/def ::customer-details
  2. (spec/keys
  3. :req [::first-name ::last-name ::residential-address]))

Hierarchical Specification

A user account is composed of a user-id and customer details. Rather than include the individual customer details, the composite customer-details specification.

The ::user-id specification is as follows

  1. (spec/def ::user-id uuid?)

The ::user-account specification

  1. (spec/def ::user-account
  2. (spec/keys
  3. :req [::user-id ::customer-details]))

The following data structure will conform to the specification

  1. {::user-id #uuid "97bda55b-6175-4c39-9e04-7c0205c709dc"
  2. ::customer-details {::first-name "Jenny"
  3. ::last-name "Jetpack"
  4. ::residential-address "Earth"}}