gpt4 book ai didi

java - 是否有 CheckStyle 规则强制 if else 关键字在 if/else 阶梯中位于同一行?

转载 作者:行者123 更新时间:2023-11-30 09:58:51 25 4
gpt4 key购买 nike

基于 this question看起来 CheckStyle 的默认模板将允许 if else 梯形图用换行符分隔 ifelse

意思是我希望这个代码被标记为违规:

if (true)
{
System.out.println("20");
}
else
if (true)
{
System.out.println("30");
}

是否有 CheckStyle 规则来防止这种情况发生?查看文档,我没有看到任何文档,如果不需要的话,我宁愿不使用通用正则表达式规则。

此外,如果我使用 GenericIllegalRegexp 模块,多行正则表达式似乎不起作用。有什么补救办法吗?

最佳答案

我不确定您是否可以轻松编写 Checkstyle 扩展,因为 Checkstyle SDK Gui 的 AST 浏览代码之间没有任何区别:

else if

else
if

在每种情况下,else 都是一个 LITERAL_ELSE,其中包含一个 if...

因此通用正则表达式 else[\t]*[\r\n]+[\t]*if 确实是一种检测此类代码的快速方法。


修复正则表达式以包含以下情况:

  • 换行符前后没有空格不是制表符
  • 这是多个换行符。

当然,您不想使用 \s 空白正则表达式,因为它本身包含换行符。将空格与返回字符分开会更清楚。


注意:在 Checkstyle 5.0beta 中,不要使用“Generic Illegal Regexp”,而是使用 "Regexp" module :
您可以将该 RegExp 模块配置为“illegalPattern”(相关严重性为“警告”),并且您不必使用任何类型的“多行”标志:正则表达式就足够了。

Regexp
Description

A check that makes sure that a specified pattern exists, exists less than a set number of times, or does not exist in the file.

This check combines all the functionality provided by RegexpHeader, GenericIllegalRegexp and RequiredRegexp, except supplying the regular expression from a file.

It differs from them in that it works in multiline mode. It's regular expression can span multiple lines and it checks this against the whole file at once. The others work in singleline mode. Their single or multiple regular expressions can only span one line. They check each of these against each line in the file in turn.


Thomas提及 in the comments :

The checkstyle AST does have line number information.

参见“Is there any Checkstyle/PMD/Findbugs rule to force “else if” to be on the same line?
(其中必须使用 custom check,而不是 regex match)。

关于java - 是否有 CheckStyle 规则强制 if else 关键字在 if/else 阶梯中位于同一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/387008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com