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 .
1 2 3 4 5 6 7 8 9 |
(ns private-example.useful-stuff) (defn- im-very-private [] (println "I'm only usable from this namespace.")) (defn call-me [] (im-very-private)) |
1 2 3 4 5 6 7 |
(ns private-example.core (:require [private-example.useful-stuff :as stuff]) (:gen-class)) (defn -main [& args] (stuff/call-me)) |
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
1 |
(ns my-proj.library) |
you might put the functions you intend to keep private in
1 |
(ns my-proj.libary.impl) |
or in
1 |
(ns my-proj.library.internal) |
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.