dimanche 28 janvier 2018

Better way of writing multiple if checks in a Clojure function?

I have a Clojure function that looks something like the following.

(defn calculate-stuff [data]
  (if (some-simple-validation data)
    (create-error data)
    (let [foo (calculate-stuff-using data)]
      (if (failed? foo)
        (create-error foo)
        (let [bar (calculate-more-stuff-using foo)]
          (if (failed? bar)
            (create-error bar)
            (calculate-response bar)))))))

Which works fine but is a little hard to read, so I was wondering if there was a more idiomatic Clojure way of writing this?

I thought about making some-simple-validation, calculate-stuff-using and calculate-more-stuff-using throw exceptions and using a try/catch block but that felt like using exceptions for control flow which didn't feel correct.

I can't let the exceptions escape this function either as I'm using it to map a seq of maps and I still want to continue processing the remainder.

I guess what I'm after is something like this?

(defn calculate-stuff [data]
  (let-with-checking-function
    [valid-data (some-simple-validation data)
     foo (calculate-stuff-using valid-data)
     bar (calculate-more-stuff-using foo)]
    failed?)                    ; this function is used to check each variable
      (create-error %)          ; % is the variable that failed
      (calculate-response bar)) ; all variables are OK

Thanks!

Aucun commentaire:

Enregistrer un commentaire