1

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 ) {
...
}
2
  • May I ask, why? Commented Jun 25, 2019 at 14:05
  • @PM77-1 because I believe that name == null is more human readable way. Commented Jun 25, 2019 at 14:06

1 Answer 1

2

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.