Skip to content

Commit 584dfd7

Browse files
authored
Skip IfElseIfConstructToSwitch when a trailing non-== null binary check is present (#1109)
Previously the trailing branch's body was silently dropped because `validatePotentialCandidate()` overwrote the disqualifying flag set by `handleNullCheck` when it could not recognise the condition. Fixes #1108
1 parent a333baa commit 584dfd7

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

src/main/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitch.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@ private SwitchCandidate(J.If if_, Cursor cursor) {
118118
return;
119119
}
120120
}
121+
if (!potentialCandidate) {
122+
return;
123+
}
121124
potentialCandidate = validatePotentialCandidate();
122125
}
123126

src/test/java/org/openrewrite/java/migrate/lang/IfElseIfConstructToSwitchTest.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -904,6 +904,32 @@ else if (obj instanceof Long l) {
904904
);
905905
}
906906

907+
@Test
908+
void noSwitchBlockWithTrailingNonEqualsBinaryCheck() {
909+
// https://github.com/openrewrite/rewrite-migrate-java/issues/1108
910+
// The trailing `else if (o != null)` is not a recognised null check and must not be silently dropped.
911+
rewriteRun(
912+
//language=java
913+
java(
914+
"""
915+
public class A {
916+
void test(Object o) {
917+
if (o instanceof String s) {
918+
System.out.println(s);
919+
} else if (o instanceof Integer i) {
920+
System.out.println(i);
921+
} else if (o instanceof Boolean b) {
922+
System.out.println(b);
923+
} else if (o != null) {
924+
System.out.println(o);
925+
}
926+
}
927+
}
928+
"""
929+
)
930+
);
931+
}
932+
907933
@Test
908934
void noSwitchBlockWhenElseBlockReturns() {
909935
rewriteRun(

0 commit comments

Comments
 (0)