What is Clojure spec?
Asked Answered
M

2

6

I could not understand the intent of clojure.spec

What kind of problems does it solve?

Why should we use it?

Malanie answered 12/6, 2016 at 9:9 Comment(0)
S
30

spec allows you to create specifications for data and functions. Specifications are at their core predicative (based on existing Clojure predicates) and structural, rather than type-based as you might see in a statically typed language. By basing spec on predicates, you can write specifications that are far more expressive than most type systems and using the same language as your code.

Specs defined on a function specify the specs for the args, the return value, and a function of the args and the return. The last one allows for checking a far greater range of things (easily) than can be checked in most type or contract systems.

Once you have defined specs, you can use them to:

  • Check whether a value is valid according to a spec
  • "Conform" a value which gives you a parsed and destructured version of the value
  • Explain in detail why a value does not conform to a spec (as a string, to stdout, or as data)
  • Enhance function docs with descriptive specs
  • Generate example data from a spec
  • Assert conformance in development but turn them off in production
  • Detect invalid calls in development or test for instrumented functions
  • Generate and run property-based tests for a spec'ed function
  • Develop tests that combine instrumentation and test generation with stubbing and mocking facilities

You can use spec to improve your development (by clarifying and documenting your intent, catching invalid calls, and asserting data validity), your testing (catch invalid calls, assert validity, generate example data, and generate automatic tests for your spec'ed functions), and your production (by using conformance for destructuring).

Additionally, Clojure core's use of specs will lead to better error messages and expanded development-time checking of core library use to find errors earlier.

Supplicatory answered 22/7, 2016 at 4:42 Comment(1)
I really liked Stuart Halloway's video on Clojure spec: youtube.com/watch?v=nqY4nUMfus8Concision
U
9

Those questions about the spec library are a bit broad, especially the "why should we use it" part. Have you read the following ?

Unreasonable answered 12/6, 2016 at 18:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.