Clojure style: defn- vs. letfn

Clojure style (and good software development in general) focuses on many small features, a subset of which are openly accessible to the external interface.

In Clojure, there seem to be several ways to do this:

(letfn [(private-a ...) (private-b ...)] (defn public-a ...) (defn public-b ...)) (defn- private-a ...) (defn- private-b ...) (defn public-a ...) (defn public-b ...) 

The letfn form looks more verbose and perhaps less flexible, but it reduces the scope of functions.

I assume letfn is only for use inside other forms when small helper functions are used only in a small area. Is that a consensus? Should it ever be used at the top level (as I saw earlier)? When should it be used?

+7
coding-style clojure
source share
3 answers

letfn intended for use in cases of mutual recursion:

 (letfn [(is-even? [n] (if (zero? n) true (is-odd? (dec n)))) (is-odd? [n] (if (zero? n) false (is-even? (dec n))))] (is-even? 42)) ;; => true 

Do not use it at the top level.

Also, do not use the defn macro anywhere except at the top level unless you have special reasons. It will be expanded to a special def form that will create and execute a global var.

+11
source share

The letfn completely different from the defn form defn . Using letfn at the top level does not give you the same defn properties, since any name bindings to functions bound inside letfn are not visible outside its scope. Binding for functions bound inside let or letfn is not available outside its lexical scope. In addition, the visibility of functions related inside letfn is independent of the order in which they are connected within this lexical domain. This does not apply to let.

+4
source share

My rules are as follows:

  • If the helper function is used in the same public, define it locally with let or letfn .
  • If it is used by several, define it at the top level with defn- .

and

  • Do not use let or letfn at the top level.
  • Do not use def or defn or defn- anywhere except at the top level.
+2
source share

All Articles