What is Clojure spec?

旧巷老猫 提交于 2019-11-30 14:34:08
Alex Miller

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!