Skip to content

Commit

Permalink
Fix pattern instanceof clean-up to remove all if statements (#2013)
Browse files Browse the repository at this point in the history
- fix
  PatternInstanceofToSwitchFixCore.PatternToSwitchExpressionOperation
  to remove all if statements at end of rewriteAST() method
- add new test to CleanUpTest21
- fixes #2012
  • Loading branch information
jjohnstn authored Feb 12, 2025
1 parent 99154cc commit 8ff6f72
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,9 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore
} else {
rewrite.replace(ifStatements.get(0), newExpressionStatement, group);
}

for (int i= 1; i< ifStatements.size(); ++i) {
rewrite.remove(ifStatements.get(i), group);
}
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,75 @@ public int foo(Object x, Object y) {
assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }, null);
}

@Test
public void testPatternInstanceofToSwitchExpression3() throws Exception {
Hashtable<String, String> options= JavaCore.getOptions();
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB);
JavaCore.setOptions(options);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
String sample= """
package test1;
public class E {
int i;
double d;
boolean b;
public int square(int x) {
return x*x;
}
public int foo(Object y) {
if (y instanceof final Integer xint) {
return xint;
}
if (y instanceof final Double xdouble) {
return square(8); // square
} else if (y instanceof final Boolean xboolean) {
throw new NullPointerException();
} else {
i = 0;
d = 0.0D;
b = false;
return 11;
}
}
}
""";
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", sample, false, null);

enable(CleanUpConstants.USE_SWITCH_FOR_INSTANCEOF_PATTERN);

sample= """
package test1;
public class E {
int i;
double d;
boolean b;
public int square(int x) {
return x*x;
}
public int foo(Object y) {
return switch (y) {
case Integer xint -> xint;
case Double xdouble -> square(8); // square
case Boolean xboolean -> throw new NullPointerException();
case null, default -> {
i = 0;
d = 0.0D;
b = false;
yield 11;
}
};
}
}
""";
String expected1= sample;

assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }, null);
}

public void testNoPatternInstanceofToSwitch1() throws Exception {
Hashtable<String, String> options= JavaCore.getOptions();
options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB);
Expand Down

0 comments on commit 8ff6f72

Please sign in to comment.