CheckStyle 模块“NeedBraces”可以吗? 使用嵌套的 if/else 块?
我们使用 CheckStyle 来强制执行我们的样式标准。 我们选择包含的样式规则之一是 NeedBraces 模块。
NeedBraces 指定每个块类型语句(例如 < code>if、else
、for
)必须有左大括号和右大括号。 然而,据我所知,它并不完全正常工作。
此示例将触发 CheckStyle 错误。
if (true)
{
System.out.println("20");
}
else
System.out.println("30");
因为 else 情况没有大括号。 但是,下一个示例无法触发 CheckStyle 错误。
if (true)
{
System.out.println("20");
}
else
if (true)
{
System.out.println("30");
}
这应该会失败,因为 else 情况下缺少大括号,但 checkstyle 让它通过。 仔细检查文档后,我找不到任何无法正常工作的原因。
所以... CheckStyle 模块“NeedBraces”可以与嵌套的 if/else 块一起使用吗? 有任何想法吗?
这个问题的答案是另一个问题:是否有规则将上述不良代码标记为违规?
We are using CheckStyle to enforce our style standards. One of the style rules we opted to include was the NeedBraces module.
NeedBraces specifies that every block type statement (such as if
, else
, for
) must have opening and closing curly braces. However, as far as I can tell it isn't working entirely correctly.
This example will trigger a CheckStyle error.
if (true)
{
System.out.println("20");
}
else
System.out.println("30");
Because the else case doesn't have braces. However, the next example fails to trigger a CheckStyle error.
if (true)
{
System.out.println("20");
}
else
if (true)
{
System.out.println("30");
}
This should have failed because of the missing braces on the else case, but checkstyle lets it pass. After double checking the documentation, I can't find any reason why this isn't working right.
So...
Can the CheckStyle module "NeedBraces" work with nested if/else blocks?
Any ideas?
The answer to this question begs another question: is there a rule to flag the above undesirable code as a violation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这是一个例外,因为尽管格式很奇怪,但你所拥有的是一个“else if”。 在这种情况下,它不应该强迫您在“if”周围放置大括号,因为您最终会得到“... else { if { ... } }
您的代码应该格式化:
I believe it is making an exception because, though formatted strangely, what you have is an "else if". It shouldn't force you to put braces around the "if" in this case because you would end up with "... else { if { ... } }
Your code should be formatted:
在第一个示例中,如果您尝试在 else 块下添加另一个语句,则需要添加大括号。 另一方面,在第二个示例中,您将在大括号内添加语句。 我相信这就是 CheckStyle 在前者中显示错误的原因,因为它容易出错。 当您确实希望将其作为 else 的一部分而不是外部时,您可能最终会在不添加大括号的情况下添加语句。
In your first example if you attempt to add another statement under your else block you will need to put braces then. On the other hand, in second example you will add the statement inside the brace. I believe thats the reason CheckStyle is showing error in the former, because its prone to errors. There is a chance that you might endup adding statement without putting braces, when you really want that as part of else not outside.