本文介绍了可以使用CheckStyle模块“NeedBraces”使用嵌套if / else块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用来执行我们的风格标准。我们选择加入的样式规则之一是 NeedBraces 模块。



指定每个块类型语句(如 if else for )必须有开始和关闭花括号。



此示例将触发CheckStyle错误。

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

因为else case没有大括号。但是,下一个示例无法触发CheckStyle错误。

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

这应该失败了,因为在else case上没有大括号,而checkstyle让它通过。经过双重检查文档,我找不到任何理由,为什么这是不正常工作。



所以...
CheckStyle模块NeedBraces可以与嵌套的if / else块一起使用吗?






此问题的答案要求:是否有一个规则标记

我相信这是一个异常,因为虽然格式奇怪,你有一个else if。在这种情况下,不应该强迫你在if周围加上大括号,因为你最终会得到... else {if {...}}



您的代码应该格式化:

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


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?

解决方案

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:

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

这篇关于可以使用CheckStyle模块“NeedBraces”使用嵌套if / else块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:26