How to use clojure.spec in library development



I’m currently creating a data-driven library. I want to use clojure.spec for input data validation. Is there any guidance or best practices of using clojure.spec for library development?


It ships with the language since 1.9, so there’s no downsides in adding it to your library, just require it and spec your public api, both functions (fdef) and data. I guess one important point is that you should try to be as liberal as possible with the inputs, i.e. don’t overspecify things, don’t fight with the open maps, etc. A perfect way to start using spec in a library is to parse args to your macros, if you have any.


Just make sure you don’t fall into the trap of overspecifying your specs.
Watch Rich’s speculation and effective programs keynotes.

They will help clarify the goals of spec.


I’m doing something similar for a library at work. The way I do it is that I have a namespace for the code, another for the specs and a test namespace where I extensively use generators test.check’s defspec utility. Then I run a single command to watch the code and execute all the tests on each code change and enter a TDD workflow for every library evolution. Generative testing based on spec is awesome.

Like the others said, don’t overspecify the inputs. The specs for the inputs specify only what’s necessary for the functions to work.

The library itself doesn’t use clojure.spec at all, so it doesn’t validate the inputs. You may want to do this depending on your use case.