Checkstyle if 语句规则

Checkstyle if statement rule

是否有任何规则可用于限制以下 if 语句:

if ( null == name ) {
...
}

基本上,null 应该总是在语句的右侧,例如

if ( name == null ) {
...
}

Sevntu 有一个名为 AvoidConstantAsFirstOperandInConditionCheck 的自定义检查,它可以满足您的需求。

$ 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.