简短的IF - ELSE声明 [英] Short IF - ELSE statement

查看:123
本文介绍了简短的IF - ELSE声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我的代码更具可读性,因此我决定使用一些简短的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将低字符数可读性混合。关键点是最容易理解的;而轻度误用语言特征是一种让读者感到困惑的明确方式,或者至少让他们做一次心理上的双重打击。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆