Skip to content

Extend UseTryWithResources to non-consecutive declarations#833

Merged
timtebeek merged 3 commits intomainfrom
tim/try-resources-non-consecutive
Mar 19, 2026
Merged

Extend UseTryWithResources to non-consecutive declarations#833
timtebeek merged 3 commits intomainfrom
tim/try-resources-non-consecutive

Conversation

@timtebeek
Copy link
Member

Adds support for transforming try/finally blocks where the variable declaration is separated from the try block by intervening statements. The recipe now uses Java 9 syntax (try (varName)) to keep the declaration in place while safely moving the resource into the try-with-resources statement.

New logic extracts the closed variable name from finally blocks and searches backwards for matching declarations, validating that the variable isn't reassigned in the intervening statements.

Includes 6 new test cases covering positive transformations and edge cases.

Add support for transforming try/finally blocks where the variable
declaration is separated from the try block by intervening statements.
Uses Java 9 syntax (try (varName)) to keep the declaration in place.
Includes validation that the variable is not reassigned between
declaration and try block.

Adds 6 new test cases covering positive and negative scenarios.
@timtebeek
Copy link
Member Author

Now that we added the ability to use Java 9 syntax it was easier to add support for non-consecutive statements.

@timtebeek timtebeek added the enhancement New feature or request label Mar 18, 2026
Verifies the recipe correctly handles a finally block with closes for
different variables, transforming each across two cycles.
Consolidate tests that exercise the same code paths: close pattern
variants, non-consecutive duplicates, and overlapping negative cases.
Copy link
Contributor

@steve-aom-elliott steve-aom-elliott left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Somehow hadn't clued into exactly the way the Java 9 syntax presents, but I suppose this works now that I understand it.

@github-project-automation github-project-automation bot moved this from In Progress to Ready to Review in OpenRewrite Mar 19, 2026
@timtebeek timtebeek merged commit e99670f into main Mar 19, 2026
1 check passed
@timtebeek timtebeek deleted the tim/try-resources-non-consecutive branch March 19, 2026 15:44
@github-project-automation github-project-automation bot moved this from Ready to Review to Done in OpenRewrite Mar 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

2 participants