简短的 IF - ELSE 语句 [英] Short IF - ELSE statement
问题描述
我试图让我的代码更具可读性,所以我决定使用一些简短的 IF 语句.
I'm trying to make my code more readable, so I decided to use some short IF statements.
这是我的代码不起作用(不是声明"):
Here's my code which doesn't work ("not a statement"):
jXPanel6.isVisible() ? jXPanel6.setVisible(true) : jXPanel6.setVisible(false);
这有什么问题吗?需要括号吗?在哪里?
What's wrong with this? Needs brackets? Where?
推荐答案
三元表达式" x ?y : z
只能用于条件赋值.也就是说,您可以执行以下操作:
The "ternary expression" x ? y : z
can only be used for conditional assignment. That is, you could do something like:
String mood = inProfit() ? "happy" : "sad";
因为三元表达式返回了一些东西(在这个例子中是 String
类型).
because the ternary expression is returning something (of type String
in this example).
它并不是真的要用作简短的内嵌 if-else
.特别是,如果各个部分不返回值或返回不兼容类型的值,则不能使用它.(因此,如果两种方法碰巧返回相同的值,您可以执行此操作,但您不应该仅出于副作用目的而调用它).
It's not really meant to be used as a short, in-line if-else
. In particular, you can't use it if the individual parts don't return a value, or return values of incompatible types. (So while you could do this if both method happened to return the same value, you shouldn't invoke it for the side-effect purposes only).
因此,正确的方法是使用 if-else 块:
So the proper way to do this would just be with an if-else block:
if (jXPanel6.isVisible()) {
jXPanel6.setVisible(true);
}
else {
jXPanel6.setVisible(false);
}
当然可以缩短为
jXPanel6.setVisible(jXPanel6.isVisible());
对我来说,后两种表达方式更具可读性,因为它们更清楚地传达了您想要做什么.(顺便说一句,你是不是把条件弄错了?不管怎样,这看起来是一个空操作,而不是一个切换).
Both of those latter expressions are, for me, more readable in that they more clearly communicate what it is you're trying to do. (And by the way, did you get your conditions the wrong way round? It looks like this is a no-op anyway, rather than a toggle).
不要将低字符数与可读性混为一谈.关键是最容易理解的;轻微滥用语言特征肯定会迷惑读者,或者至少让他们在心理上做两件事.
Don't mix up low character count with readability. The key point is what is most easily understood; and mildly misusing language features is a definite way to confuse readers, or at least make them do a mental double-take.
这篇关于简短的 IF - ELSE 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!