I have a group of numeric functions in Clojure that I want to validate the arguments for. There are numerous types of arguments expected by the functions, such as positive integers, percentages, sequences of numbers, sequences of non-zero numbers, and so on. I can validate the arguments to any individual function by:
- Writing validation code right into
the function. - Writing a general
purpose function, passing it the
arguments and expected types. - Writing a general purpose macro,
passing it the arguments and
expected types. - Others I haven’t thought of.
Some Lisp code by Larry Hunter is a nice example of #3. (Look for the test-variables macro.)
My intuition is that a macro is more appropriate because of the control over evaluation and the potential to do compile-time computation rather than doing it all at run time. But, I haven’t run into a use case for the code I’m writing that seems to require it. I’m wondering if it is worth the effort to write such a macro.
Any suggestions?
Clojure already has (undocumented, maybe subject-to-change) support for pre- and post-conditions on
fns.Kind of ugly though.
I’d probably write a macro just so I could report which tests failed in a succinct way (quote and print the test literally). The CL code you linked to looks pretty nasty with that enormous case statement. Multimethods would be better here in my opinion. You can throw something like this together pretty easily yourself.
Then: