How to set configuration parameters in clojure library? -
i writing clojure library , wondering best practice setting configuration parameters of library.
many libraries (like in clojure-contrib) use global level parameter *buffer-size*
user can set calling set!
on them. not seems best way me creates global state , there chances of name collision.
the other way pass parameters in every function call dependent on them. if there many parameters map of them can used instead of passing individual ones.
as example, let's writing cache library.
using first approach have global parameters *cache-size*, *expiry-time*, *cache-dir*
etc. user set!
s these (or not , let them default) , calls functions (set-in-cache id obj)
, (get-from-cache id)
.
using second approach, user first create map of parameters , passes every call
(def cache-parameters {:cache-size 1000 :expiry-time: 1440 :cache-dir "c:\\cache"}) (set-in-cache cache-parameters id obj) (get-from-cache cache-parameters id)
so way preferred way in clojure , why?
actually cannot set!
things c.c.io
's *buffer-size*
unless install thread-local binding them binding
, with-bindings
etc. there's handful of vars thread-local bindings installed lower level clojure machinery, such *warn-on-reflection*
, *read-eval*
, making them set!
-able @ top-level; user-defined vars not set!
-able @ top-level. root binding of var can changed e.g. alter-var-root
, intern
, def
, .bindroot
..., should used sparingly.
as rebindable vars vs. explicit parameters part of question: going explicit parameters ok , preferable, because of increased maintainability of functions display pieces of data depend on. being said, if piece of configuration set once, used virtually every function call within app / library ever after, might make saner code define earmuffed var, document , put config in (and might 1 of rare cases changing var's root binding outside of form defines might ok).
to summarise, use best judgement, if unsure -- err on side of explicit parameter passing.
Comments
Post a Comment