Add recipe to avoid repeated Pattern.compile calls - #1005
Open
raj7-dev wants to merge 2 commits into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What's changed?
Adds a new
AvoidRepeatedPatternCompilerecipe that moves method-localPattern.compile()calls with constant regex literals into reusableprivate static final Patternfields.The current implementation:
Pattern.compile(String)with literal regexes.Pattern.compile(String, int)when the flags are constant.Unit tests cover both positive and negative cases.
What's your motivation?
Repeatedly calling
Pattern.compile()for the same constant regular expression recompiles the regex on each method invocation.This recipe moves such patterns to reusable class-level constants.
Pattern.compile()too many times #622Anything in particular you'd like reviewers to focus on?
I'd particularly appreciate feedback on:
Pattern.compile()cases that should be handled.Anyone you would like to review specifically?
No specific reviewer.
Have you considered any alternatives or workarounds?
The initial implementation intentionally keeps the detection conservative rather than attempting to evaluate arbitrary expressions.
Dynamic regexes such as:
or:
are left unchanged.
This avoids moving expressions to class scope when their value depends on runtime state.
Any additional context
Recipe-specific tests pass locally:
7 tests pass successfully.
I also ran:
and generated the required
recipes.csventry.The full repository test suite currently fails locally in unrelated RPC tests. Existing Python tests attempt to install
openrewrite==8.90.0, which is unavailable from the configured Python package index.These failures are unrelated to
AvoidRepeatedPatternCompile.Checklist
./gradlew buildlocally, and committed any resulting changes torecipes.csv