Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,15 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
if (statement instanceof J.If) {
J.If ifStatement = (J.If) statement;
if (ifStatement.getElsePart() != null && endsWithReturnOrThrow(ifStatement.getThenPart())) {
J.If newIf = ifStatement.withElsePart(null);
Statement elsePart = ifStatement.getElsePart().getBody();
if (elsePart instanceof J.If) {
J.If elseIf = (J.If) elsePart;
if (isSimpleThenBlock(elseIf.getThenPart())) {
return statement;
}
}

J.If newIf = ifStatement.withElsePart(null);
if (elsePart instanceof J.Block) {
J.Block elseBlock = (J.Block) elsePart;
endWhitespace.set(elseBlock.getEnd());
Expand Down Expand Up @@ -90,6 +97,18 @@ public J.Block visitBlock(J.Block block, ExecutionContext ctx) {
return maybeAutoFormat(b, alteredBlock, ctx);
}

private boolean isSimpleThenBlock(Statement thenPart) {
if (thenPart instanceof J.Return) {
return true;
}
if (thenPart instanceof J.Block) {
J.Block block = (J.Block) thenPart;
return block.getStatements().size() == 1 &&
block.getStatements().get(0) instanceof J.Return;
}
return false;
}

private boolean endsWithReturnOrThrow(Statement statement) {
if (statement instanceof J.Return || statement instanceof J.Throw) {
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,11 +357,9 @@ class Test {
int foo(String str) {
if ("one".equals(str)) {
return 1;
}
if ("two".equals(str)) {
} else if ("two".equals(str)) {
return 2;
}
if ("three".equals(str)) {
} else if ("three".equals(str)) {
return 3;
}
return Integer.MAX_VALUE;
Expand Down Expand Up @@ -519,8 +517,7 @@ class Test {
String process(int value) {
if (value < 0) {
throw new IllegalArgumentException("Negative value");
}
if (value == 0) {
} else if (value == 0) {
return "zero";
}
return "positive";
Expand Down
Loading