1
\$\begingroup\$

I have a piece of code that tries to get some data from a different services, falling back to the next one if previous fails.

The code look a little bit ugly, though. Any suggestions on how to rewrite it in a more concise way?

(defn get-data [query]
  (let [data-cached (get-data-from-cache query)
        data-service-1 (if (nil? data-cached)
                         (get-data-service-1 query)
                         data-cached)
        data-service-2 (if (nil? data-service-1)
                         (get-data-service-2 query)
                         data-service-1)
        data (if (nil? data-service-2)
                   (get-data-service-3 query)
                   data-service-2)]
    data))
\$\endgroup\$
1
  • 2
    \$\begingroup\$ The title of your post should be the function/purpose of your code. \$\endgroup\$
    – SirPython
    Commented Feb 21, 2015 at 3:08

1 Answer 1

1
\$\begingroup\$

Perhaps or macro could be used here:

(defn get-data [query]
   (or (get-data-from-cache query) 
       (get-data-service-1 query) 
       (get-data-service-2 query) 
       (get-data-service-3 query)))

or short-circuits, so the first match will return and the rest will not be evaluated

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.