try-with-resources and null resource

Tim Peierls tim at peierls.net
Thu Jan 27 06:47:54 PST 2011


On Thu, Jan 27, 2011 at 4:10 AM, Stephen Colebourne <scolebourne at joda.org>wrote:

> Funnily enough, I have proposed similar analogies in the past. But
> they are seductively dangerous. How many devs looking at a foreach
> loop know it uses an iterator? Or an index if its an array? The same
> applies here.
>

I'm not saying that people _should_ make analogies to interpret unfamiliar
constructs. I'm saying they _do_, and that ignoring that fact leads to
designs that surprise everyone but the experts.



> A similar case is closures/lambdas. There, the analogy is to inner
> classes, yet after much thought, Oracle has come to the same
> conclusion I did - that "this" within a lambda should not act as
> "this" does in an inner class. Sometimes, we have to break with the
> analogy to get the right result.
>

This was a case of designers letting go of an analogy. I don't think user
expectations were ignored here. (Quite the contrary.)



> try (InputStream stream =
>     getClass().getResourceAsStream("/com/foo/mightOrMightNotExist")) {
>  if (stream != null) {
>    readStream(stream);
>  }
> }
>
> This will fail ATM, because of that null, yet the code is perfectly clear
> and readable. What's the alternative?
>

Bruce Chapman already made a good case for not calling close on null
resource. This code *would* work in that case.



> Executive summary: C# has got it right. Null resources should be silently
> be accepted.
>

I don't know about C#, but I like the formulation that can be sloppily
summarized as "t-w-r calls close on non-null resources".

Perhaps we violently agree?


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.
>

Is anyone actually against the "don't call close on null resource"? My first
reaction was against, but Bruce convinced me easily.

I'm against NPE on null initializer.

--tim



More information about the coin-dev mailing list