extract method nullable check: ensure correct exist statement chosen (IDEA-132706)

This commit is contained in:
Anna Kozlova
2014-11-13 12:35:04 +01:00
parent 1360541825
commit 350c0b2a0a
4 changed files with 73 additions and 5 deletions
@@ -712,11 +712,21 @@ public class ExtractMethodProcessor implements MatchProvider {
(PsiMethodCallExpression)((PsiAssignmentExpression)assignmentExpression.getExpression()).getRExpression().replace(myMethodCall);
}
declareNecessaryVariablesAfterCall(myOutputVariable);
PsiIfStatement ifStatement =
(PsiIfStatement)myElementFactory.createStatementFromText(myHasReturnStatementOutput || (myGenerateConditionalExit && myFirstExitStatementCopy instanceof PsiReturnStatement &&
((PsiReturnStatement)myFirstExitStatementCopy).getReturnValue() != null)
? "if (" + varName + "==null) return null;"
: "if (" + varName + "==null) return;", null);
PsiIfStatement ifStatement;
if (myHasReturnStatementOutput) {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
}
else if (myGenerateConditionalExit) {
if (myFirstExitStatementCopy instanceof PsiReturnStatement && ((PsiReturnStatement)myFirstExitStatementCopy).getReturnValue() != null) {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return null;", null);
}
else {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) " + myFirstExitStatementCopy.getText(), null);
}
}
else {
ifStatement = (PsiIfStatement)myElementFactory.createStatementFromText("if (" + varName + "==null) return;", null);
}
ifStatement = (PsiIfStatement)addToMethodCallLocation(ifStatement);
CodeStyleManager.getInstance(myProject).reformat(ifStatement);
}
@@ -0,0 +1,24 @@
import java.util.List;
class Test {
List<Pojo> things;
void foo() {
while(true) {
<selection>Pojo x = things.get(0);
if(x.it > 0) {
break;
}
things.remove(x);</selection>
System.out.println(x.it);
}
}
static class Pojo {
double it;
Pojo(double w) {
it = w;
}
}
}
@@ -0,0 +1,30 @@
import java.util.List;
class Test {
List<Pojo> things;
void foo() {
while(true) {
Pojo x = newMethod();
if (x == null) break;
System.out.println(x.it);
}
}
private Pojo newMethod() {
Pojo x = things.get(0);
if(x.it > 0) {
return null;
}
things.remove(x);
return x;
}
static class Pojo {
double it;
Pojo(double w) {
it = w;
}
}
}
@@ -455,6 +455,10 @@ public class ExtractMethodTest extends LightCodeInsightTestCase {
doTest();
}
public void testNullableCheckBreak() throws Exception {
doTest();
}
public void testSimpleArrayAccess() throws Exception {
doTest();
}