Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
3fe1ea9
feat: create new recipe Ternary operators should not be nested
ps-twill May 6, 2023
0ac3205
cleanup imports
ps-twill May 6, 2023
f3b83bc
update todo comment to complete solution
ps-twill May 6, 2023
2d31776
add another todo true part
ps-twill May 6, 2023
6ddccf8
Add more tests
ps-twill May 7, 2023
67f4d01
try something different
ps-twill May 7, 2023
e80ae76
reorder tests
ps-twill May 7, 2023
44b6f66
revert to return extra block
ps-twill May 7, 2023
fab13fa
add todo
ps-twill May 7, 2023
5495fd3
helpers and dont reuse old return (maybe ids will conflict?)
pstreef May 7, 2023
b4409cb
add truePart
pstreef May 7, 2023
0741ab1
and remove todo
pstreef May 7, 2023
f4d10b4
add todo
pstreef May 7, 2023
a45963b
override tags
pstreef May 7, 2023
8d817c3
Fix tests
pstreef May 8, 2023
6fa7287
remove todo
pstreef May 8, 2023
00eb8f8
remove todo & rename method
pstreef May 8, 2023
a942e5e
add more tests
pstreef May 8, 2023
dadbc95
add license
pstreef May 8, 2023
bbdc5de
add test with whitespace
pstreef May 9, 2023
d42304c
Merge remote-tracking branch 'origin/main' into feature/recipe-ternar…
pstreef May 18, 2023
e376b96
Handle ternary in lambda
pstreef May 18, 2023
4f29673
cleanup
pstreef May 18, 2023
8bd105f
cleanup
pstreef May 18, 2023
83ddd72
only when nested ternary
pstreef May 18, 2023
226bad0
add @Issue link
pstreef May 18, 2023
d024aa1
recursive approach for multi level ternaries. Add failing test for co…
pstreef May 23, 2023
ad746b5
Merge remote-tracking branch 'origin/main' into feature/recipe-ternar…
pstreef May 27, 2023
97bc24a
getting there!
pstreef May 30, 2023
f1ab378
getting there!
pstreef May 30, 2023
a880914
fix another test
pstreef May 30, 2023
eb65ba1
add Objects.equals handling
pstreef May 30, 2023
8dc7e3e
add binary conditions
pstreef May 30, 2023
a0dea8e
add more tests
pstreef May 30, 2023
81c40a0
remove todo
pstreef May 30, 2023
8fb6fa3
Merge remote-tracking branch 'origin/main' into feature/recipe-ternar…
pstreef May 30, 2023
885a61a
end visiting of subtree at CompilationUnit
pstreef May 30, 2023
c096386
use javaVersion in tests
pstreef May 30, 2023
4ff8cbd
fixes
pstreef May 30, 2023
5d0b21b
add constant handling for binaries
pstreef May 30, 2023
896784f
other side of equals must be constant
pstreef May 30, 2023
905207b
use helper
pstreef May 30, 2023
6c9e11a
Merge remote-tracking branch 'origin/main' into feature/recipe-ternar…
pstreef May 31, 2023
1aeba33
fix build with latest rewrite:main
pstreef May 31, 2023
123f7bb
Merge branch 'openrewrite:main' into feature/recipe-ternary-operator-…
pstreef Aug 21, 2023
f7beb4c
remove default duration
pstreef Aug 22, 2023
8d57951
Ignore Objects.equals when finding switch expression candidates as it…
pstreef Aug 22, 2023
e8a0848
Add more test nesting
pstreef Aug 22, 2023
5b47f8a
Merge branch 'main' into feature/recipe-ternary-operator-should-not-b…
timtebeek Aug 22, 2023
2a0cf6e
Add two DocumentExamples
timtebeek Aug 22, 2023
a2d96ab
add links to issues
pstreef Aug 22, 2023
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
@@ -0,0 +1,92 @@
package org.openrewrite.staticanalysis;

import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaSourceFile;
import org.openrewrite.java.tree.Space;
import org.openrewrite.java.tree.Statement;
import org.openrewrite.marker.Markers;


public class TernaryOperatorsShouldNotBeNested extends Recipe {
@Override
public String getDisplayName() {
return "Ternary operators should not be nested";
}

@Override
public String getDescription() {
return "Just because you can do something, doesn’t mean you should, and that’s the case with nested ternary operations. " +
"Nesting ternary operators results in the kind of code that may seem clear as day when you write it, " +
"but six months later will leave maintainers (or worse - future you) scratching their heads and cursing.\n\n" +
"Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.";
}

@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(5);
}

@Override
public Set<String> getTags() {
return Collections.singleton("RSPEC-3358");
}

@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TernaryOperatorsShouldNotBeNestedVisitor();
}

private static class TernaryOperatorsShouldNotBeNestedVisitor extends JavaVisitor<ExecutionContext> {

final JavaTemplate iffTemplate = JavaTemplate.builder(this::getCursor, "if(#{any(boolean)}) {}").build();

@Override
public @Nullable J visit(@Nullable final Tree tree, final ExecutionContext executionContext) {
J result = super.visit(tree, executionContext);
if (tree instanceof JavaSourceFile) {
result = (J) new RemoveUnneededBlock().getVisitor().visit(result, executionContext);
}
return result;
}

@Override
public J visitReturn(final J.Return retrn, final ExecutionContext executionContext) {
J possiblyTernary = retrn.getExpression();
if (possiblyTernary instanceof J.Ternary) {
J.Ternary ternary = (J.Ternary) possiblyTernary;
if (ternary.getFalsePart() instanceof J.Ternary || ternary.getTruePart() instanceof J.Ternary) {
J.If iff = retrn.withTemplate(
iffTemplate,
retrn.getCoordinates().replace(),
ternary.getCondition()
);
iff = iff.withThenPart(blockOf(returnOf(ternary.getTruePart())));
J result = blockOf(iff, returnOf(ternary.getFalsePart()));
return autoFormat(result, executionContext);
}
}
return super.visitReturn(retrn, executionContext);
}
}

private static J.Return returnOf(Expression expression) {
return new J.Return(Tree.randomId(), Space.EMPTY, Markers.EMPTY, expression);
}

private static J.Block blockOf(Statement... statements) {
return J.Block.createEmptyBlock().withStatements(Arrays.asList(statements));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package org.openrewrite.staticanalysis;

import static org.openrewrite.java.Assertions.java;

import org.junit.jupiter.api.Test;
import org.junitpioneer.jupiter.ExpectedToFail;
import org.openrewrite.Issue;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

class TernaryOperatorsShouldNotBeNestedTest implements RewriteTest {

@Override
public void defaults(RecipeSpec spec) {
spec.recipe(new TernaryOperatorsShouldNotBeNested());
}

@Test
void doReplaceNestedOrTernaryWithIfFollowedByTernary() {
rewriteRun(
//language=java
java(
"""
class Test {
public String determineSomething(String a, String b) {
return "a".equals(a) ? "a" : "b".equals(b) ? "b" : "nope";
}
}
""",
"""
class Test {
public String determineSomething(String a, String b) {
if ("a".equals(a)) {
return "a";
}
return "b".equals(b) ? "b" : "nope";
}
}
"""
)
);
}

@Test
void doReplaceNestedOrTernaryRecursive() {
rewriteRun(
//language=java
java(
"""
class Test {
public String determineSomething(String a, String b, String c) {
return "a".equals(a) ? "a" : "b".equals(b) ? "b" : "c".equals(b) ? "c" :"nope";
}
}
""",
"""
class Test {
public String determineSomething(String a, String b, String c) {
if ("a".equals(a)) {
return "a";
}
if ("b".equals(b)) {
return "b";
}
return "c".equals(b) ? "c" : "nope";
}
}
"""
)
);
}

@Test
void doReplaceNestedAndTernaryWithIfThenTernary() {
rewriteRun(
//language=java
java(
"""
class Test {
public String determineSomething(String a, String b) {
return "a".equals(a) ? "b".equals(b) ? "b" : "a" : "nope";
}
}
""",
"""
class Test {
public String determineSomething(String a, String b) {
if ("a".equals(a)) {
return "b".equals(b) ? "b" : "a";
}
return "nope";
}
}
"""
)
);
}

@Test
void doReplaceNestedAndOrTernaryWithIfThenTernaryElseTernary() {
rewriteRun(
//language=java
java(
"""
class Test {
public String determineSomething(String a, String b, String c) {
return "a".equals(a) ? "b".equals(b) ? "b" : "a" : "c".equals(c) ? "c" : "nope";
}
}
""",
"""
class Test {
public String determineSomething(String a, String b, String c) {
if ("a".equals(a)) {
return "b".equals(b) ? "b" : "a";
}
return "c".equals(c) ? "c" : "nope";
}
}
"""
)
);
}

@Issue("todo")
@ExpectedToFail("only directly returned ternaries are taken into account")
@Test
void doReplaceNestedOrAssignmentTernaryWithIfElse() {
rewriteRun(
//language=java
java(
"""
class Test {
public void doThing(String a, String b) {
String result = "a".equals(a) ? "a" : "b".equals(b) ? "b" : "nope";
System.out.println(result);
}
}
""",
"""
class Test {
public void doThing(String a, String b) {
String result;
if ("a".equals(a)) {
result = "a";
}
else {
result = "b".equals(b) ? "b" : "nope";
}
System.out.println(result);
}
}
"""
)
);
}

}