[LANG-1656] Add Supplier-based variants of firstNonBlank and firstNonEmpty for short-circuit evaluation #1469
+152
−0
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.
Thanks for your contribution to Apache Commons! Your help is appreciated!
Before you push a pull request, review this list:
mvn
; that'smvn
on the command line by itself.Description of Issue
The PR addresses the JIRA issue titled 'Short-circuit operation of firstNonBlank and firstNonEmpty', a minor feature request originally proposed by Zhengkai Wang.
The existing methods
firstNonBlank
andfirstNonEmpty
in StringUtils.java evaluate all input strings immediately. This can lead to extra computational overhead when some arguments are expensive to compute, such as those involving remote API calls or database queries.The feature request aims to introduce supplier-based variants of these methods, which support lazy evaluation and short-circuit behaviour.
Implementation
To resolve this, two new methods were added to StringUtils:
Introducing new methods instead of modifying existing ones ensures backward compatibility with existing firstNonBlank and firstNonEmpty implementations. It avoids method overloading ambiguity and also creates a clear separation between eager and lazy variants.
Validation and Testing
testFirstNonBlankSupplier()
andtestFirstNonEmptySupplier()
validate:testFirstNonBlankSupplierLazyEvaluation()
andtestFirstNonEmptySupplierLazyEvaluation()
verify short-circuit behavior using AtomicBoolean flags.