清空if语句 [英] Empty if-statements
问题描述
通过空if语句,我的意思是这样的(注意分号):
By "empty if-statement", I mean something like this (note the semicolon):
if (condition);
我在考虑应用程序时遇到了麻烦。使用while循环可以执行以下操作:
I'm having trouble thinking of an application for this. With a while loop you can do this:
while (callUntilReturnsFalse());
但是if-statement没有这样的申请。更重要的是,Java编译器在面对这样的语句时不会发出错误或警告。这可能导致大型和无声问题,特别是有一个漫长而复杂的陈述:
But there's no such application for an if-statement. What's more, the Java compiler doesn't issue an error or a warning when confronted with such a statement. This can lead to large and silent problems, especially with a long and convoluted statement:
if ((functionA() && functionB(getFoo()) ||
checkForComplexCondition(arg1, arg2, getBar(getFoo())));
{
doStuff();
}
我的问题是:为什么Java允许这样做?更重要的是,我可以启用一个选项,以便在发生这种情况时发出警告?
My question is: why is this allowed in Java? And, more importantly, can I enable an option to cause a warning when this happens?
(这个问题是之前询问过的关于C#的问题,它确实发出警告,但我希望找到一种方法使用Java引发警告。)
(This question was asked before with regards to C#, which does issue a warning, but I was hoping to find a way to cause a warning with Java.)
推荐答案
为什么在Java中允许这样做?
请参阅 Java语言规范(14.6。空语句):
空语句什么都不做。
An empty statement does nothing.
它只是被允许而且相当于(并且会被翻译为):
It's simply allowed and it's equivalent to (and will be translated to):
if (condition) { }
这意味着,如果条件为真,则什么都不做。
Which means, if the condition is true, do nothing.
如果你正在使用eclipse,你可以看看这里,你可能会发现一些有用的东西(我不确定分号终结符有这样的选项):
If you're using eclipse, you can look here, you might find something useful (I'm not sure there exists such an option for semicolon terminator):
Window →首选项→ Java →编译器→错误/警告
正如@nullptr在他的回答中所指出的,存在IDE警告,你需要设置警告 on 空语句。
As @nullptr pointed out in his answer, there exist an IDE warning for this, you need to set warning on Empty statement.
这篇关于清空if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!