简体   繁体   English

Checkstyle规则,避免不满足条件

[英]Checkstyle rule to avoid not condition

I am using checkstyles and I'd like to define the rule like where it displays a warning in case someone uses not condition under if ... else ... block. 我正在使用checkstyles,我想定义规则,例如在有人使用if ... else ...块下not条件的情况下显示警告的if ... else ... For example: 例如:

if (!employeeNotExist) { 
  // code
} else {
  // code
}

Reason being it's good to have only positive condition for readability 原因是最好只具有积极的可读性条件

Is there ready made module for this under checkstyle or some custom checkstyle rule needs to be written for this? 是否在checkstyle下为此提供了现成的模块,或者为此需要编写一些自定义checkstyle规则?

我不认为此检查是在checkstyle本身中定义的,但是您始终可以使用扩展插件之一,即https://github.com/sevntu-checkstyle/sevntu.checkstyle ,您可以在此处找到所需的内容: 这里

Checkstyle cannot do this out of the box. Checkstyle无法开箱即用。 So if using a third-party library is no option for you, you will have to write a custom check . 因此,如果不适合使用第三方库,则必须编写自定义检查 If it's any comfort: This would be quite a simple case of custom check. 如果可以的话:这将是一个非常简单的自定义检查案例。

The best you can do out of the box is to configure a DescendantToken check like this (works in Eclipse-CS; DescendantToken checks are complex low-level checks which require understanding of the AST to configure, please see the linked documentation for more information): 开箱即用最好的方法是配置DescendantToken检查(在Eclipse-CS中工作; DescendantToken检查是复杂的低级检查,需要了解AST才能配置,请参阅链接的文档以获取更多信息) :

<module name="DescendantToken">
    <property name="tokens" value="LITERAL_IF"/>
    <property name="limitedTokens" value="LNOT"/>
    <property name="minimumDepth" value="2"/>
    <property name="maximumDepth" value="2"/>
    <property name="maximumNumber" value="0"/>
    <property name="maximumMessage" value="Consider changing this to a
            positive condition for better readability."/>
</module>

This approach is somewhat crude, as it will not detect if there is an else block, and it also flags method calls such as if (!map.isEmpty()) . 这种方法有些粗糙,因为它不会检测是否存在else块,并且还会标记诸如if (!map.isEmpty())类的方法调用。 But it covers your if (!employeeNotExist) case. 但这涵盖了您的if (!employeeNotExist)案例。 It will also flag conditions like !(a || b) , but those can be rewritten to !a && !b . 它还将标记条件,如!(a || b) ,但可以将其重写为!a && !b

So, all in all, it's far from perfect, but this is the closest you're going to get with out-of-the-box Checkstyle. 因此,总的来说,它远非完美,但这是开箱即用的Checkstyle最接近的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM