clojure-spec

onetom 2022-04-19T08:25:28.738089Z

at https://youtu.be/dtGzfYvBn3w?t=6346 there is a slide, saying: > • DO NOT use check, instrument or (turn on) assert in production > • they are for making sure your program works - use in advance > • but spec can play a runtime role > • validating inputs from external systems or users The args conformance and exception throwing feature of instrument seems like a very useful guard to have even for production code, especially, when it's checking relationships between the input arguments. It would help us pinpoint code-paths in our code, which is not covered by tests or specs. Q1: what does "validating inputs from external systems or users" refer to? using function :pre [...] conditions? what spec functions should i use, if not s/assert? it seems like that the unconditional s/assert* was made to be used in :pre` conditions... Q2: is there a way to do something like instrument, but only for checking :args, so i wouldn't need to repeat such logic as function :pre conditions?

Linus Ericsson 2022-04-19T09:04:49.658499Z

Q1: I would suggest using a construct like

(when-not (s/valid ::spec data) 
  (throw (ex-info "error in..." {:error-data error-data}))
because asserts (and pre-posts i think) can be disabled by various options to the JVM. Be explicit with your throws after validation. Q2: I would not recommend using instrument or pre when validating input from users or other systems. Rather make this validation a separate step in the processing of data. The way to handle incorrect data can differ between various systems and sources of data.

👍 2
onetom 2022-04-19T11:54:51.583859Z

i didn't know u can turn off :pre & :post conditions with *assert*, thanks!

Aron 2022-04-20T05:42:39.706989Z

do I have to throw if something is not valid?

Santiago 2022-04-20T06:12:00.026579Z

You can also use something like Failjure instead of throwing, but I think the general way is to make use of JVM exceptions

Linus Ericsson 2022-04-20T14:30:31.291829Z

Re throw or not - it depends on how your application handles errors in inputdata. Usually this is very application specific. Usually it's not good to use exceptions for flow control.

Aron 2022-04-21T01:59:54.239509Z

There is no reason for validation or for tests to throw, not in cases that I expect.