try-with-resources and null resource
Gernot Neppert
mcnepp02 at googlemail.com
Thu Jan 27 04:19:16 PST 2011
I think the best compromise between 'concise' and 'readable' would be:
URL resource = getClass().getResource("/com/foo/mightOrMightNotExist");
if (resource != null) {
try (InputStream stream = url.openStream())
{
readStream(stream);
}
}
Actually, I think that Class.getResourceAsStream is a notable
exception with its null-semantics.
>From looking at my codecase I can see that the overwhelming majority
of try-finally blocks act on non-nullable resources, such as:
all sorts of newly allocated InputStreams, OutputStreams, Readers, Writers.
java.sql.* related resources such as Statements, ResultSets.
java.util.concurrent.Lock
Thus, if I could vote I'd say built-in support for nullable resources
was not necessary.
2011/1/27 Stephen Colebourne <scolebourne at joda.org>:
>
> InputStream stream =
> getClass().getResourceAsStream("/com/foo/mightOrMightNotExist");
> if (stream != null) {
> try (InputStream stream2 = stream) {
> readStream(stream2);
> }
> }
>
> That now works, but is significantly less clear to read, more verbose
> and more prone to accidental refactoring.
>
> In fact, there was a bug when I first typed this email, as I wrote
> readStream(stream) rather than readStream(stream2). In this case, it
> would have no bad effects, but other similar cases might.
>
> In fact, I'd probably still write:
> InputStream stream =
> getClass().getResourceAsStream("/com/foo/mightOrMightNotExist");
> try {
> if (stream != null) {
> readStream(stream);
> } finally {
> org.apache.commons.lang.IOUtils.closeQuietly(stream);
> }
> }
>
> as it is clearer than the t-w-r version.
>
>
> Executive summary: C# has got it right. Null resources should be
> silently be accepted.
>
> Priority. Initially I said this didn't matter much to me. With this
> new use case (straight out of my day job yesterday), I really care
> about my conclusion now. Please reconsider the semantics based on this
> use case.
>
> Stephen
>
>
More information about the coin-dev
mailing list