Bug 362415 - New warning to detect unnecessary toString() on String
Summary: New warning to detect unnecessary toString() on String
Status: NEW
Alias: None
Product: JDT
Classification: Eclipse Project
Component: Core (show other bugs)
Version: 3.8   Edit
Hardware: PC Windows 7
: P3 enhancement (vote)
Target Milestone: ---   Edit
Assignee: Ayushman Jain CLA
QA Contact:
URL:
Whiteboard:
Keywords:
: 44787 (view as bug list)
Depends on:
Blocks:
 
Reported: 2011-10-29 23:03 EDT by Paul Benedict CLA
Modified: 2011-12-08 09:50 EST (History)
4 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
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.