Bug 119142 - "Extract Local Variable" should never replace multiple expressions containing "new"
Summary: "Extract Local Variable" should never replace multiple expressions containing...
Status: RESOLVED DUPLICATE of bug 27740
Alias: None
Product: JDT
Classification: Eclipse Project
Component: UI (show other bugs)
Version: 3.1   Edit
Hardware: PC Linux
: P3 normal (vote)
Target Milestone: ---   Edit
Assignee: Markus Keller CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2005-12-02 17:58 EST by Luke Hutchison CLA
Modified: 2006-03-22 05:11 EST (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Luke Hutchison CLA 2005-12-02 17:58:59 EST
Initial code:

if (x) {
    d0.add(new Vector<Integer>());
    d1.add(new Vector<Integer>());
}

Select first occurrence of "new Vector<Integer>()" and replace with local variable a0, with the box checked to replace all instances of the expression with the variable:

Vector<Integer> a0 = new Vector<Integer>();
if (x) {
  d0.add(a0);
  d1.add(a0);
}

This is of course never going to be semantically correct.

The refactoring engine can't in general know if the given expression will have side effects like this.  However this is a fairly prominent case to catch as an exception -- if the expression contains a "new", then the checkbox to replace all instances should be greyed-out.  I almost didn't notice that the refactorer did this, because it has always worked for every expression I tried before.  

Perhaps there needs to be a warning displayed in the dialog box if there is a method call in the expression and more than one instance of the expression is being replaced, which says that it is the programmer's responsibility to ensure that the function has no side effects.

In general, I think it would be very valuable for JDT to explicitly know when a method has side effects and when it doesn't.  This may be uncomputable in the general case, but it is certainly possible to prove when a function *doesn't* have side-effects.
Comment 1 Olivier Thomann CLA 2005-12-02 19:00:49 EST
Move to JDT/UI
Comment 2 Luke Hutchison CLA 2005-12-13 02:15:02 EST
Actually maybe there should just be a warning whenever a function call is contained within the expression.  Another example that shouldn't be optimized out:

// Choose two random haplotypes
int[] haplotype1 = haplogroupResults.get((int)(haplogroupResults.size() * Math.random())).haplotype;
int[] haplotype2 = haplogroupResults.get((int)(haplogroupResults.size() * Math.random())).haplotype;
Comment 3 Markus Keller CLA 2006-03-22 05:11:48 EST

*** This bug has been marked as a duplicate of 27740 ***