Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid overriding variable names

Tags:

clojure

On a particular namespace I am working on I am beginning to run out of function names. Is there a way to get a warning like the one I get if I override a symbol from another namespace if I reuse a symbol which is already bound to a function in the same namespace?

like image 504
Hamza Yerlikaya Avatar asked Sep 16 '11 22:09

Hamza Yerlikaya


1 Answers

If this is enough of a problem that you'd be willing to replace a (set of) core macro(s), you could try this approach:

(ns huge.core
  (:refer-clojure :exclude [defn]))

(defmacro defn [name & defn-tail]
  (assert (nil? (resolve name))
          (str "Attempting to redefine already defined Var "
               "#'" (.name *ns*) "/" name))
  `(clojure.core/defn ~name ~@defn-tail))

Then any attempt to redefine an existing Var with defn will fail:

user=> (defn foo [] :foo)
#'user/foo
user=> (defn foo [] :bar)
AssertionError Assert failed: Attempting to redefine already defined Var #'user/foo
(nil? (resolve name))  user/defn (NO_SOURCE_FILE:2)

You could similarly replace defmacro; in that case you would have to call clojure.core/defmacro when defining your own variant.

Plain, unadorned def is a special form and receives magic treatment from the compiler, so you could still overwrite existing Vars with it. If you would like to guard against name clashes on that flank too, you could switch to something like defvar (used to be available in clojure.contrib.def) with a similar custom assert.

like image 130
Michał Marczyk Avatar answered Oct 03 '22 21:10

Michał Marczyk