Java inspection: Don't look for assignment chains in 'switch' and loop statements in "Move return to computation" inspection (IDEA-121153)

This commit is contained in:
Pavel Dolgov
2016-09-07 18:48:46 +03:00
parent bed73576d5
commit f3d22142cd
3 changed files with 57 additions and 1 deletions
@@ -383,7 +383,8 @@ public class ReturnSeparatedFromComputationInspection extends BaseJavaBatchLocal
PsiJavaToken rBrace = codeBlock.getRBrace();
if (rBrace != null) {
PsiStatement lastNonEmptyStatement = getPrevNonEmptyStatement(rBrace, removeCompletely);
if (lastNonEmptyStatement == null || hasChainedAssignmentsInScope(flow, resultVariable, lastNonEmptyStatement)) {
if (lastNonEmptyStatement == null ||
isIfBranch(codeBlock) && hasChainedAssignmentsInScope(flow, resultVariable, lastNonEmptyStatement)) {
return false;
}
if (moveTo(lastNonEmptyStatement, returnAtTheEnd)) {
@@ -507,6 +508,11 @@ public class ReturnSeparatedFromComputationInspection extends BaseJavaBatchLocal
return ExpressionUtils.computeConstantExpression(condition) == Boolean.TRUE;
}
private static boolean isIfBranch(@NotNull PsiCodeBlock codeBlock) {
final PsiElement parent = codeBlock.getParent();
return parent instanceof PsiBlockStatement && parent.getParent() instanceof PsiIfStatement;
}
private Set<PsiBreakStatement> getBreaks(@NotNull PsiStatement targetStatement) {
if (breakStatements == null) {
breakStatements = new THashMap<>();
@@ -0,0 +1,23 @@
// "Move 'return' closer to computation of the value of 'n'" "true"
class T {
int f(int a) {
int n = -1;
switch (a) {
case 0:
case 1:
case 2:
return n;
case 10:
case 20:
return n + 1;
case 30:
case 40:
case 50:
return 2;
case 90:
return 3;
default:
throw new IllegalArgumentException();
}
}
}
@@ -0,0 +1,27 @@
// "Move 'return' closer to computation of the value of 'n'" "true"
class T {
int f(int a) {
int n = -1;
switch (a) {
case 0:
case 1:
case 2:
break;
case 10:
case 20:
n = n + 1;
break;
case 30:
case 40:
case 50:
n = 2;
break;
case 90:
n = 3;
break;
default:
throw new IllegalArgumentException();
}
r<caret>eturn n;
}
}