gradle-baseline icon indicating copy to clipboard operation
gradle-baseline copied to clipboard

[FR] Error-prone check to unpack nested try/with constructors into compound statements

Open carterkozak opened this issue 4 years ago • 3 comments

What happened?

In some cases it may be possible for nested closeables to skip closing delegates:

try (InputStream is = new GZIPInpuutStream(new FileInputStream(file))) {
   // etc
}

What did you want to happen?

We can avoid this risk by restructuring the try block:

try (FileInputStream fis = new FileInputStream(file);
     InputStream is = new GZIPInpuutStream(fis)) {
   // etc
}

carterkozak avatar Mar 06 '21 04:03 carterkozak

Sounds like the biggest annoyance with introducing this is the intermediary variable name colliding with variable names already declared in other scopes. Should it be allowed (or even convention) to prefix the intermediary name with an underscore? E.g.

try (FileInputStream _fis = new FileInputStream(file);
     InputStream is = new GZIPInpuutStream(_fis)) {
   // etc
}

tjb9dc avatar Mar 08 '21 16:03 tjb9dc

One of the two hardest problems in cs ;-)

Fortunately we should have access to all the variables in scope, I'd prefer not to underscore-prefix but come up with more descriptive names.

carterkozak avatar Mar 08 '21 16:03 carterkozak

That makes sense as we typically reserve the underscore-prefix for unused parameters. Hopefully something like fisDelegate is available...

tjb9dc avatar Mar 08 '21 17:03 tjb9dc