Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decide on a style for destructuring with :keys (using symbols and/or keywords) #257

Open
timspc opened this issue Jul 25, 2024 · 1 comment

Comments

@timspc
Copy link

timspc commented Jul 25, 2024

Hi,

Does anyone else have an opinion on the better style in these situations?

Situation A.

;; style A1
(defn f 
  [{:keys [one two three}]
  (+ one two three)

;; style A2
(defn f 
  [{:keys [:one :two :three}]
  (+ one two three)

Situation B. (Namespaced keywords using an alias)

(require '[my.named.space :as space])

;; style B1
(defn f 
  [{:keys [two three] 
    ::space/keys [one]}]
  (+ one two three))

;; style B2
(defn f 
  [{:keys [::space/one :two :three]}]
  (+ one two three))

;; style B3
(defn f 
  [{:keys [::space/one two three]}]
  (+ one two three))

;; style B4
(defn f 
  [{:keys [my.named.space/one two three]}]
  (+ one two three))

I strongly prefer style 1 (A1 and B1) because:

  • The main point of destructuring is to introduce symbols into the current scope in a concise way. In my opinion it looks wrong to introduce a symbol by writing a keyword. To me it looks almost as strange as writing (fn [:one :two] one).
  • Destructuring with :keys is the only place that I can think of where you can introduce a symbol using a keyword. So for consistency with all the other places where you can introduce a symbol we shouldn't do it here either.

Some reasons I can think of to prefer style 2 (A2 and B2) are:

  • Style A2 allows better searching for keyword usage across a project (biggest advantage in my opinion as it's more than stylistic).
  • Styles B2 and B3 are the most concise of the options in situation B (concision being a core benefit of destructuring). But style B3 is strange because it mixes keywords and symbols, therefore style B2 is preferable.
  • If style B2 is preferred in situation B, then for consistency we should use style A2 in situation A. Beyond consistency reasons, it reduces the need to refactor if we change that function to accept some namespaced keywords.

Does anyone know if there are many clojure projects that use styles A2 and B2?

Does anyone have an opinion either way or is it just me?

@seancorfield
Copy link
Collaborator

seancorfield commented Jul 25, 2024

I strongly prefer style 1 (A1 and B1)

Yes, definitely. Whenever I see destructuring with keywords, I always have to do a double-take and remind myself it is actually valid, even if very unusual. 👀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants