bbatsov / clojure-style-guide

A community coding style guide for the Clojure programming language
https://guide.clojure.style
4.02k stars 279 forks source link

"Oneliners" with and without documentation #118

Open danskarda opened 9 years ago

danskarda commented 9 years ago

I would like to clarify (and maybe enhance) formatting of simple functions.

According to current standard, following example is bad

(defn foobar 
  [x] (-> x foo bar baz))

correct indentation in two lines is

(defn foobar [x] 
  (-> x foo bar baz))

or in three lines with newline:

(defn foobar 
  [x] 
  (-> x foo bar baz))

I see there two inconsistencies, because a) multiarity functions allow similar indentation, so simply killing [x y] arity should lead to correct formatting.

(defn foobar 
  ([x] (-> x foo bar baz))
  ([x y] (-> x foo (bar y) baz)))

and b) neither two liner or three-liner play nice with docstring. There I would expect to see short version in three lines. Again, removing docstring should lead to correct formatting.

(defn foobar
   "Does foo, bar and baz to x"
    [x] (-> x foo bar baz))

I apologize in advance for nitpicking and starting worst code formatting flamewar ever.

arrdem commented 9 years ago

So the easy fix is just to outlaw use of defn and insist that everyone write (def ... (fn* ... )) the indentations and forms of which are well understood and agreed upon. Sorta kidding sorta not.

I think that the style choice in the first two is clear as you seem to agree. For short argument vectors same line as the defn seems to be a very common coding style at present and is presented in several of the fine Clojure books. While I agree that your 3rd example is somewhat awkward, it does lend itself to adding a docstring and for that reason is the style which I have forced myself to adopt in recent projects. The single line formatting of the 4th example while tempting is something else which I personally strive to avoid. -> allows us to escape nesting, and my style is to insist that sequential forms in an arrow context each occur on a new line no matter how short the entire form.

I have some sympathy for the 5th snippet, however I would again prefer a newline for each of the symbol, the docstring, the args and the body.

danskarda commented 9 years ago
(defn foobar [x]
  (do something usefull))

probably comes from our Emacs / Common Lisp habits. Many times it seduced me to write.

(defn foobar [x]
  "Does something useful"
  (do something usefull))

Which is incorrect, because it is not documentation, but ignored expression.

But lets get back to some more intellectually challenging problems than indendation ;)

arrdem commented 9 years ago

Heh. Indeed. Eastwood has a checker for exactly such docstring misplacement bugs :stuck_out_tongue: