Using “using”

November 5, 2009

I presented my own code for review in the last PMR group meeting and thankfully came off very lightly. However Nick Day who is currently doing a lot of Clojure work picked me up on something. I had many lines of code similar to:

XPathDocument xPathDocument = new XPathDocument(new StringReader(source));

and he was worried that I was not closing my string reader after use. After a bit of looking around I see that the code should be refactored into:

XPathDocument xPathDocument = null;
using (StringReader sr = new StringReader(source)) {
  xPathDocument = new XPathDocument(sr);

This ensures that the StringReader can be disposed of as soon as it has been used to create the XPathDocument. I am not at all surprised that Nick would spot this as it reminds me of the first Clojure macro that I finally got – though that was for a HTTP request.

Of course I could always have done the more conventional (and Java like):

StringReader sr = new StringReader(source);
XPathDocument xPathDocument = new XPathDocument(sr);

but I find the first way far more elegant and clear and it ensures that the resources are cleaned up no matter what – even if the creation of the XPathDocument throws exceptions.