Private Functions in Clojure

Clojure developers coming from Object Oriented backgrounds know how useful it is to separate implementation details from functions and methods that are supposed to be used by other coders. Java has public and private methods. This allows devs to limit usage and visibility of functions that are not meant to be used directly.

There are two options in Clojure for keeping functions private. First, you can use a special macro, defn- . defn-  works just like defn , except that the function is only visible inside the current namespace. This makes the function private in the Java sense to the term.

Here’s an example of its use in a file named useful_suff.clj  and core.clj .

The other option is to make a separate namespace and keep implementation details in the implementation namespace. For example, if you have a public set of functions in

you might put the functions you intend to keep private in

or in

This approach is cleaner than using defn-  functions, though it does not enforce misuse of the private functions.

If you want to see a specific Clojure tutorial, please let me know on Twiter.

Leave a Reply

Your email address will not be published. Required fields are marked *