NoValueOfOnStringType: keep String.valueOf when the argument can be null - #1022
Open
Niloyyy wants to merge 1 commit into
Open
NoValueOfOnStringType: keep String.valueOf when the argument can be null#1022Niloyyy wants to merge 1 commit into
Niloyyy wants to merge 1 commit into
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.
The problem
String.valueOf(s)equalssonly whensis not null — for a nullStringit produces"null". The recipe removed the call for anyString-typed argument that wasn't a method invocation, so a nullable variable lost its conversion:Running both:
Method invocations were already excluded, and the reason is the same one that applies here — the value may be null. Identifiers, field accesses and casts are no safer. This also lines up the behavior with the recipe's own description, which says the simplification applies "when the argument to
String#valueOf(arg)is a string literal".The change
For
Stringarguments, require the expression to be demonstrably non-null — a non-null literal, or a string concatenation.The one thing I wanted to avoid was over-correcting. Inside a concatenation the removal is safe even for nulls, because
+already renders a null operand as"null":My first attempt blocked that too, which would have lost a legitimate simplification. So
removeValueOfForStringConcatenationnow acceptsStringarguments alongside primitives, and that case keeps working.Tests
Full suite locally on JDK 21: 2277 tests, 0 failures.