Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.

Bug 362415

Summary: New warning to detect unnecessary toString() on String
Product: [Eclipse Project] JDT Reporter: Paul Benedict <pbenedict>
Component: CoreAssignee: Ayushman Jain <amj87.iitr>
Status: NEW --- QA Contact:
Severity: enhancement    
Priority: P3 CC: amj87.iitr, avijayr, deepakazad, ulrich.everling
Version: 3.8   
Target Milestone: ---   
Hardware: PC   
OS: Windows 7   
Whiteboard:

Description Paul Benedict CLA 2011-10-29 23:03:02 EDT
Build Identifier: 20110916-0149

After doing some method refactoring, I ended up with code that had toString() calls on a returning String. 

Before:
String s = returnsUUID().toString();
After:
String s = returnsString().toString();

That's redundant code. It would be nice to catch these kind of useless calls for String.toString() with a compiler warning option.

Reproducible: Always
Comment 1 Deepak Azad CLA 2011-10-31 14:53:50 EDT
This is essentially a search for method references and hence I would rather fix bug 209145 as that would be a more general solution for all methods.
Comment 2 Deepak Azad CLA 2011-10-31 14:55:37 EDT
Also note that a call to String#toString() is harmless as the method is defined as..

public String toString() {
	return this;
}
Comment 3 Paul Benedict CLA 2011-10-31 15:05:29 EDT
If bug 209145 can be fixed, perhaps then Clean Up could be enhanced to remove these spurious invocations.
Comment 4 Missing name Mising name CLA 2011-12-08 03:37:05 EST
This is independent of bug #209145 because String is final so toString() cannot be overridden.

The warning should be raised for x.toString() whenever x is an expression of type java.lang.String

The Quick Fix should remove the method call, leaving x alone.

Of course x is not entirely equivalent with x.toString() because,
when x happens to evaluate to null, x.toString() throws a NullPointerException.
Comment 5 Ayushman Jain CLA 2011-12-08 04:29:18 EST
*** Bug 44787 has been marked as a duplicate of this bug. ***
Comment 6 Missing name Mising name CLA 2011-12-08 09:50:23 EST
When x is an expression of type String, and x.toString() is used as a StatementExpression, then x alone may or may not be suitable as a StatementExpression.
If not, the Quick Fix of omitting the method call and keeping x is inappropriate; instead, a quick fix should consider omitting x as well but keeping side effects if any.

The warning itself makes sense anyway.