Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let bloat or idiomatic clojure?

Tags:

idioms

clojure

Being new to clojure I struggle with finding an idiomatic style for different code constructs.

In some cases my let bindings contain most of the code of a function. Is this bloat, some misunderstanding of clojure philosophy or idiomatic and just fine?

Here is a sample testcase to demonstrate. It tests an add/get roundtrip to some storage repository. Does the long let look wierd?

(deftest garden-repo-add-get
  (testing "Test garden repo add/get"
    (let [repo (garden/get-garden-repo)
          initial-garden-count (count (.list-gardens repo))
          new-garden (garden/create-garden "Keukenhof")
          new-garden-id (.add-garden repo new-garden)
          fetched-garden (.get-garden repo new-garden-id)]
      (is (= (+ initial-garden-count 1) (count (.list-gardens repo))))
      (is (= (.name new-garden) (.name fetched-garden))))))
like image 992
4ZM Avatar asked Jul 22 '26 18:07

4ZM


1 Answers

Main problem I see with your let code, and is the usual case, is you're using lots of intermediate variables whom only have names in order to exist in the let form.

The best approach to avoid the overbloat is to use the arrow macro -> or ->>

For instance you can avoid repo intermediate variable with

initial-garden-count (-> (garden/get-garden-repo)
                         (.list-gardens)
                         count)

None the less, in your particular case you're using all your intermediate variables in your test validation, so you need them on the let statement anyway. Maybe new-garden-id is the only intermediate you can avoid:

fetched-garden (->> (.add-garden repo new-garden)
                    (.get-garden repo))

Or using the approach suggested by Chiron:

fechted-gaden (.get-garden repo (.add-garden repo new-garden))
like image 182
guilespi Avatar answered Jul 25 '26 19:07

guilespi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!