What is the use case of *compile-files* in Clojure?

Viewed 100

I'm reading lots of Clojure code and see some interesting things (at least for me). Here is some code that I encountered:

(when-not *compile-files*
  (.addAppender (Logger/getRootLogger) (create-appender)))

Why/when would you use this dynamic binding *compile-files* ?

2 Answers

This binding is set from compile. The way the compilation works with Clojure is to basically "run" NS to compile for its top level side effects in regard to where Clojure puts things (e.g. ns, defn, def, ...) and store the results as .class files.

This also means, that if your code contains "real side effects" at top level, they will be executed at compile time too, which usually surprises people.

So if you have "dangerous" things you want to do once the ns loads, you can protect from execution at compile time by checking for *compile-files*.

There are other means to "hide" things from the compiler. E.g. a common usecase is to use delay for defs that trigger side effects like creating a database connection.

Related