三元运算符用于增加变量 [英] Ternary Operator use to increase variable

查看:72
本文介绍了三元运算符用于增加变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此,请使用三元运算符:

Is it a good practice to use the ternary operator for this:

answersCounter = answer.length != 0 ? ++answersCounter : answersCounter;

这是我一直问自己的问题经常发生。或者,使用常规的if语句更好吗?对我来说,这看起来很整齐。

This is a question that I always asked myself as it happens quite often. Or, is it better to use a normal if statement? For me, this looks much cleaner in one line.

推荐答案

这只是意见,但我认为像您这样写增量

This is just opinion, but I think that writing the increment like you have it is somewhat poor style.

将变量分配给自身的预增量版本会有些混乱。对我来说,最好的代码是最清晰的(必要时对优化的点头除外),有时简洁导致清晰,有时却没有(请参见用Perl编写的任何东西……我在说,sorta)。

Assigning a variable to a pre-incremented version of itself is a little bit confusing. To me, the best code is the clearest (excepting nods to optimization where necessary), and sometimes brevity leads to clarity and sometimes it does not (see anything written in Perl... I kid, sorta).

您曾经遇到过以下编程技巧问题:

Have you ever had the programming trick question of:

int i = 5;
i += i++ + i;

还是类似的东西?并且您认为自己谁将永远需要知道结果如何,因为您何时将变量分配给自身的前后增量版本?我的意思是,您永远不会在真实代码中看到它,对吧?

Or something similar? And you think to yourself who would ever need to know how that works out since when would you ever assign a variable to the pre/post increment version of itself? I mean, you would never ever see that in real code, right?

嗯,您只是提供了一个示例。尽管它是可解析的,但它不是惯用语言,也不比简单的 if 清晰。

Well, you just provided an example. And while it is parseable, it is not idiomatic and not clearer than a straight forward if.

例如

if (answer.length != 0) answersCounter++;

当然,有些人不喜欢 if 不带花括号的语句,并且不喜欢不带换行符的花括号,这可能就是您使用三进制结尾的原因。需要重新评估具有编码样式的内容,尽管会导致(主观的)较差的代码,从而避免返回一些回车符。

Of course, some people don't like if statements with out braces, and don't like braces without newlines, which is probably how you ended up with the ternary. Something with the coding style needs to be re-evaluated though if it is resulting in (subjectively) worse code to avoid a few carriage returns.

再次,这仅是观点,当然不是规则。

Again, this is opinion only, and certainly not a rule.

这篇关于三元运算符用于增加变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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