Merge pull request #3938 from VoidxHoshi:master

[java] Modify SimplifiedTernary to meet the missing case #3603 #3938
This commit is contained in:
Andreas Dangel
2022-04-28 15:03:28 +02:00
5 changed files with 88 additions and 73 deletions

View File

@ -1291,12 +1291,11 @@ public void foo() throws Exception {
Look for ternary operators with the form `condition ? literalBoolean : foo`
or `condition ? foo : literalBoolean`.
These expressions can be simplified respectively to
`condition || foo` when the literalBoolean is true
`!condition && foo` when the literalBoolean is false
or
`!condition || foo` when the literalBoolean is true
`condition && foo` when the literalBoolean is false
These expressions can be simplified as follows:
* `condition ? true : expr` simplifies to `condition || expr`
* `condition ? false : expr` simplifies to `!condition && expr`
* `condition ? expr : true` simplifies to `!condition || expr`
* `condition ? expr : false` simplifies to `condition && expr`
]]>
</description>
<priority>3</priority>
@ -1305,9 +1304,9 @@ or
<property name="xpath">
<value>
<![CDATA[
//ConditionalExpression[not(PrimaryExpression/*/Literal) and (Expression/PrimaryExpression/*/Literal/BooleanLiteral)]
|
//ConditionalExpression[not(Expression/PrimaryExpression/*/Literal) and (PrimaryExpression/*/Literal/BooleanLiteral)]
//ConditionalExpression
[(Expression|.)/PrimaryExpression/*/Literal/BooleanLiteral]
[not((Expression|.)/PrimaryExpression/*/Literal/NullLiteral)]
]]>
</value>
</property>
@ -1330,6 +1329,10 @@ public class Foo {
public void test4() {
final boolean otherValue = condition ? something() : false; // can be as simple as condition && something();
}
public boolean test5() {
return condition ? true : false; // can be as simple as return condition;
}
}
]]>
</example>

View File

@ -53,12 +53,12 @@ public class Foo {
</test-code>
<test-code>
<description>condition ? true : false</description>
<expected-problems>0</expected-problems>
<description>#3603 condition ? true : false</description>
<expected-problems>1</expected-problems>
<code><![CDATA[
public class Foo {
public boolean test() {
return condition ? true : false; // Existing rule
return condition ? true : false;
}
}
]]></code>