Oh, also see the source code for with-open :
http://github.com/richhickey/clojure/blob/master/src/clj/clojure/core.clj#L2542

and also note that it allows you to declare bindings for opening
connections in sequence, and will take care of closing them in the
reverse order.

And to answer your question about writing 2 macros if you have
different APIs, no no :

  * either use protocols if you work on the master branch
  * either use multimethods

that is, use polymorphism :-)

2010/4/21 Laurent PETIT <laurent.pe...@gmail.com>:
> Hi,
>
> Something I don't understand: if the call to (API/getConnection ...)
> fails, there is nothing to close, right ?
>
> So for the problem of ensuring that any open connection is always
> closed, the following pattern seems enough:
>
> (try
>  (let [conn (API/getConnection ..)]
>     XXX)
>  (finally (API/closeConnection conn)))
>
> In XXX you can do your business job, maybe catching exceptions, etc.,
> but that is not the same intent as ensuring pairs of open/close calls
> in any case.
>
> Smart java frameworks such as SpringFramework do the exact same thing
> by using Interface callbacks encapsulating the XXX "real interesting
> code".
>
> The less verbose way of doing this is clojure's with-open macro.
> Though you would have, as Alex pointed out, to create your own variant
> of with-open to accomodate your particular API for closing the
> connection.
>
> Or, if you use master, you could write the protocol-aware version of
> with-open :-)
>
>
> 2010/4/21 ka <sancha...@gmail.com>:
>> Hi,
>>
>> I'm using an API to connect to a server which does not provide
>> constructors, just static methods to get & close connections.
>>
>> How can I do something like ...
>>
>> (try
>>  (let [conn (API/getConnection ..)]
>>    (....))
>>  (catch ..)
>>  (finally (if conn (API/closeConnection conn))))
>>
>> Problem is that conn is unavailable in the finally context.
>>
>> Is there any easy workaround which doesn't involve defing a global
>> conn.
>>
>> - Thanks
>>
>> --
>> You received this message because you are subscribed to the Google
>> Groups "Clojure" group.
>> To post to this group, send email to clojure@googlegroups.com
>> Note that posts from new members are moderated - please be patient with your 
>> first post.
>> To unsubscribe from this group, send email to
>> clojure+unsubscr...@googlegroups.com
>> For more options, visit this group at
>> http://groups.google.com/group/clojure?hl=en
>

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to