Skip to content

Clojure style guide

Christopher Small edited this page Mar 30, 2018 · 5 revisions

It would be nice if we could agree on some things regarding coding style for Clojure.

Code style

  • Clojure Spec is good. Use it.
  • Always start simple/understandable, then deal with performance as needed.
  • If m is a hash map, use (:key m) instead of (m :key) wherever possible. The former will still work if m is re-implemented as a record, but not the latter. Also, the former will return nil if m is nil, whereas the latter would raise an exception.
  • Prefer maps over records unless they become preferable for some reason down the road (for performance for instance). Note that while still simple they don't have the same level of structural sharing, so unless you need the performance better to avoid.
  • Prefer fn over #(...) if the function/lambda definition will span multiple lines

Formatting style

I highly recommend using Parinfer, because it makes writing Clojure so much easier. By inferring parenthesis placement from indentation, writing Clojure and all its parens becomes as easy (easier really) and visual as writing Python. This also ends up constraining how we indent and style and code. It's somewhat important then that everyone write Parinfer compliant code, or Parinfer will end up trying to fix it when someone else starts editing using Parinfer, and it doesn't always "fix" correctly.

Where decisions related to Parinfer aren't involved, we can follow from this guide: https://github.com/bbatsov/clojure-style-guide.

A couple of emphases/tweaks/additions:

  • If you have to split a s-exp between multiple lines:
    • do not start a lambda on the first line (as second expression element) unless you can finish it on that line
Clone this wiki locally