Reputation: 2293
Is there any rule that I can use for restricting following if
statements :
if ( null == name ) {
...
}
Basically, null
should be always on the right side of statement e.g.
if ( name == null ) {
...
}
Upvotes: 1
Views: 450
Reputation: 2201
Sevntu has a custom check called AvoidConstantAsFirstOperandInConditionCheck
which does what you want.
$ cat TestClass.java
public class TestClass {
void method() {
if ( null == name ) {} // violation
if ( name == null ) {} // OK
}
}
$ cat TestConfig.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<property name="charset" value="UTF-8"/>
<module name="TreeWalker">
<module name="com.github.sevntu.checkstyle.checks.coding.AvoidConstantAsFirstOperandInConditionCheck" />
</module>
</module>
$ java -jar checkstyle-8.9-sevntu-1.29.0-all.jar -c TestConfig.xml TestClass.java
Starting audit...
[ERROR] TestClass.java:3: Constant have to be second operand of '=='. [AvoidConstantAsFirstOperandInCondition]
Audit done.
Checkstyle ends with 1 errors.
Upvotes: 2