Reputation: 730
In Clojure for the Brave and True, chapter 8, a function called if-valid
is proposed (then rejected) to abstract away the repetitive parts of validation checks:
(defn if-valid
[record validations success-code failure-code]
(let [errors (validate record validations)]
(if (empty? errors)
success-code
failure-code)))
The author explains that the function in its above state won't work as success-code
and failure-code
will be evaluated on each if-valid
call. My understanding is, that the if
function's test will return true or false, and that dictates whether the success or failure code runs. Please can someone explain how both then and else portions of the if
will be evaluated for each if-valid
call?
Upvotes: 1
Views: 69
Reputation: 91857
Suppose that this function is used as follows:
(if-valid my-data validators
(println "Data accepted")
(throw (Exception. "Bad data :(")))
This is no good, because function arguments must be evaluated before they can be passed to the function. So, the side effects of first printing "Data accepted" and then throwing an exception will both be performed every time, before this function gets a chance to run validations at all.
Upvotes: 3