Bug 582049 - [extract method] Extract method fails to report semantics change when finally present
Summary: [extract method] Extract method fails to report semantics change when finally...
Status: NEW
Alias: None
Product: Incubator
Classification: Eclipse Project
Component: e4 (show other bugs)
Version: unspecified   Edit
Hardware: PC Windows 10
: P3 normal (vote)
Target Milestone: ---   Edit
Assignee: E4 Inbox CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2023-06-08 08:12 EDT by Lorenzo Puglioli CLA
Modified: 2023-06-09 07:02 EDT (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Lorenzo Puglioli CLA 2023-06-08 08:12:17 EDT
Steps To Reproduce:
1. Create a class with this code:

public class TestExtractMethod {

	public void testMethod() {
		TestClass testClass = null;
		try {
			//Start here
			testClass = testClassFactoryPotentiallyFailing();
			methodPotentiallyThrowingException();
			//End here
		} finally {
			if (testClass != null) {
				testClass.doSomething();
			}
		}

	}

	private TestClass testClassFactoryPotentiallyFailing() {
		return new TestClass();
	}

	private void methodPotentiallyThrowingException() {
		//something...
	}

	private static class TestClass {

		public void doSomething() {
			//something
		}

	}

}

2. Select the lines between "Start here" and "End here" comments
3. Apply the refactor "Extract Method"
4. The refactor will complete without errors or warnings, and the code will become:
...
	public void testMethod() {
		TestClass testClass = null;
		try {
			testClass = extracted();
		} finally {
			if (testClass != null) {
				testClass.doSomething();
			}
		}

	}

	private TestClass extracted() {
		TestClass testClass;
		//Start here
		testClass = testClassFactoryPotentiallyFailing();
		methodPotentiallyThrowingException();
		//End here
		return testClass;
	}
...

The generated code is wrong: in case of exception during "methodPotentiallyThrowingException", the assignment to local variable "testClass" in method "testMethod" will be skipped, so the method "doSomething" (maybe a release of resources...) won't be called.
An error or warning before applying the refactor should be done.
Comment 1 Lorenzo Puglioli CLA 2023-06-09 07:02:22 EDT
The problem can be extended. Generally speaking, the rule could be:
"If the returned value from the extracted method is assigned to a variable declared outside of the refactored code block, a warning should always be raised"