I understand that the binding form allows rebindable dynamic scoping in clojure. So far the only uses I’ve seen it used for is for I/O such as with print where *out* is rebound to what ever writer you would like at the time.
I would like to see examples that truly take advantage of the power of binding where other facilities really don’t work. Personally I’ve only used it in cases where passing around a user supplied object to all the functions was really tedious. Basically a situation where I am trying to create a context that the helper functions uses. (Similar to this case When should one use the temporarily-rebind-a-special-var idiom in Clojure? ) To be more specific, I was relying on the user to create a dynamic binding to the *db* var to allow the database functions to know what to operate on. This was particularly useful when the user needs to write lots of nested calls to the database functions. Typically, I’m OK if I need to write macros to make things easier for myself, but to require the user to do so seems bad. That being said, I try to avoid doing so as much as possible.
What are some other good use cases for ‘binding’ that I can copy and incorporate into my code?
I use bindings for two reasons:
testing
I am working on a distributed system with several components that communicate by sending messages over message exchanges. These exchanges have global names, which I have defined like such:
These constants are used in a number of places to send messages to the right place. To test my code, part of my test suite runs code that uses the actual message exchanges. However, I don’t want my testing to interfere with the actual system.
To solve this, I wrap my testing code in a
bindingcall that overrides these constants:Inside of this
bindingfunction, I can call any code that uses the constants and it’ll use the overridden values.using global resources
Another way I use bindings is to “fix” the value of a global or singleton resource inside a particular scope. Here’s an example of a RabbitMQ library I wrote, where I bind the value of a RabbitMQ
Connectionto the symbol*amqp-connection*so that my code can use it:The implementation of
with-connectionis quite simple:Any code in my RabbitMQ library can use the connection in
*amqp-connection*and assume that it is a valid, openConnection. Or use the(current-connection)function, which throws a descriptive exception when you forgot to wrap your RabbitMQ calls in awith-connection: