三元运算符使用哪种编码风格?

发布于 2024-07-08 12:33:21 字数 414 浏览 10 评论 0原文

如果它很短,我将其保留在单行中。 最近,我一直在使用这种样式来处理较长或嵌套的三元运算符表达式。 一个人为的例子:

$value = ( $a == $b ) 
            ? 'true value # 1'
            : ( $a == $c )
                ? 'true value # 2'
                : 'false value';

您个人使用哪种风格,或者认为哪种风格最具可读性?

编辑: (关于何时使用三元运算符)

我通常避免使用超过 2 层的深度三元运算符。 当我在 PHP 模板脚本中回显变量时,我更喜欢 2 级深度三元运算符而不是 2 级 if-else。

I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:

$value = ( $a == $b ) 
            ? 'true value # 1'
            : ( $a == $c )
                ? 'true value # 2'
                : 'false value';

Personally which style you use, or find most readable?

Edit: (on when to use ternary-operator)

I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

俏︾媚 2024-07-15 12:33:21

通常要避免使用三元运算符,但这种形式非常易读:

  result = (foo == bar)  ? result1 :
           (foo == baz)  ? result2 :
           (foo == qux)  ? result3 :
           (foo == quux) ? result4 : 
                           fail_result;

这样,条件和结果就放在同一行上,并且很容易浏览并理解发生了什么。

The ternary operator is generally to be avoided, but this form can be quite readable:

  result = (foo == bar)  ? result1 :
           (foo == baz)  ? result2 :
           (foo == qux)  ? result3 :
           (foo == quux) ? result4 : 
                           fail_result;

This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.

一梦等七年七年为一梦 2024-07-15 12:33:21

我尽量不使用三元运算符来编写嵌套条件。 它违背了可读性,并且与使用条件相比没有提供额外的价值。

只有当它可以放在一行中,并且它的含义非常清楚时,我才会使用它:

$value = ($a < 0) ? 'minus' : 'plus';

I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional.

Only if it can fit on a single line, and it's crystal-clear what it means, I use it:

$value = ($a < 0) ? 'minus' : 'plus';
沐歌 2024-07-15 12:33:21

有时使用的一种风格是这样的,因为它没有被提及,所以我提出了这种风格:

$result = ($x == y)
        ? "foo"
        : "bar";

..但通常只有在将所有内容放在一行上使其太长的情况下。 我发现有 = ? :所有的排列使它看起来更整洁。

a style I sometimes use, which I'm bringing up since it hasn't been mentioned, is like this:

$result = ($x == y)
        ? "foo"
        : "bar";

..but usually only if putting it all on one line makes it too long. I find that having the = ? : all line up makes it look neater.

生来就爱笑 2024-07-15 12:33:21

就我个人而言,我仅在适合一行的情况下使用三元运算符。 如果它需要跨越,那么是时候回到过去了

if else if else

Personally, I only use the ternary operator if it fits on one line. If it need to span, then it's time for the good old

if else if else
傲性难收 2024-07-15 12:33:21

PHP 嵌套三元运算符的行为有所不同。

此语法通过了以下所有测试。
基于 http://deadlytechnology.com/web-development-tips/php-三元语法/

$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');

请参阅:http://au.php.net/ternary

示例#3“非明显的三元行为”解释了为什么以下内容在 PHP 中不起作用。

$x = 1;
$y = 2;
$z = 3;   
$myvar = ($x == $y) 
       ? "foo" 
       : ($x == $z) 
         ? "bar" 
         : "none";  
$myvar == 'none'; // Good

$x = 1;
$y = 2;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Good

$x = 1;
$y = 1;
$z = 3;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

$x = 1;
$y = 1;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

PHP nested ternary operators behave differently.

This syntax passes all the following tests.
Based on http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');

.

See: http://au.php.net/ternary

Example #3 "Non-obvious Ternary Behaviour" explains why the following does not work in PHP.

$x = 1;
$y = 2;
$z = 3;   
$myvar = ($x == $y) 
       ? "foo" 
       : ($x == $z) 
         ? "bar" 
         : "none";  
$myvar == 'none'; // Good

$x = 1;
$y = 2;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Good

$x = 1;
$y = 1;
$z = 3;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

$x = 1;
$y = 1;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!
逆夏时光 2024-07-15 12:33:21

三元运算符是编写简单 if 语句的简短而有效的方法。 它们不应该嵌套或难以阅读。 请记住:您编写的软件一次,但它会被阅读 100 次。 读起来应该比写起来容易。

ternary operators are short effective ways to write simple if statements. They shouldn't be nested or difficult to read. Remember: You write the software once but is is read 100 times. It should be easier to read than write.

对你而言 2024-07-15 12:33:21

我倾向于将条件括在括号中: (a == b) ? 1:0

I tend to enclose the condition in parentheses : (a == b) ? 1 : 0

永言不败 2024-07-15 12:33:21

我会不同意普遍的观点。 我的条件运算符风格有点像 Imran。 如果它完全适合一根线,我就把它保留在一根线上。 如果它不能完全适合一行,我会破坏它,但我只使用一个制表符(4 个空格;我将 VS 设置为为制表符插入空格)进行缩进。 我不会立即跳转到 if-else,因为很多时候条件运算符在上下文中更有意义。 (但是,如果它在上下文中没有意义,我就不会使用它。)

此外,我不嵌套条件运算符。 到那时,我确实发现它太难阅读了,是时候采用更详细的 if-else 样式了。

I'll dissent with the common opinion. I'm sort of like Imran with my conditional operator style. If it fits cleanly on one line, I keep it on one line. If it doesn't fit cleanly on one line, I do break it, but I use only a single tab (4 spaces; I have VS set to insert spaces for tabs) for the indent. I don't immediately jump to if-else, because a lot of the time the conditional operator makes more sense contextually. (If it doesn't make sense contextually, however, I simply don't use it.)

Also, I don't nest conditional operators. At that point, I do find it too difficult to read, and it's time to go to the more verbose if-else style.

沉鱼一梦 2024-07-15 12:33:21

三元条件可以使代码更干净、更优雅,最重要的是,可以帮助您强调正确的事情并避免重复。 考虑使用它们,但不要因此降低代码的可读性。 在 VB.NET 中:

    'before refactoring 
    If x = 0 Then                    ' If-Then-Else puts emphasis on flow control
        label = "None"
    Else
        label = Foo.getLabel(x)      '  If-Then-Else forces repeat of assignment line
    End If

    'after refactoring    
    label = If(x = 0, "None", Foo.getLabel(x)) ' ternary If puts emphasis on assignment

请注意,“它的可读性较差”与“我不习惯看到它”不是一回事。

The ternary conditional can make code cleaner and more elegant, and most importantly, help you put emphasis on the right things and avoid repeating yourself. Consider using them, but do not make the code less readable by doing so. In VB.NET:

    'before refactoring 
    If x = 0 Then                    ' If-Then-Else puts emphasis on flow control
        label = "None"
    Else
        label = Foo.getLabel(x)      '  If-Then-Else forces repeat of assignment line
    End If

    'after refactoring    
    label = If(x = 0, "None", Foo.getLabel(x)) ' ternary If puts emphasis on assignment

Note that "it is less readable" is not the same thing as "I'm not used to seeing that".

紫南 2024-07-15 12:33:21

“人为的例子”是我如何缩进它,除了我会从左边距缩进,而不是基于 ( 或上面一行中的任何内容。

对于三元贬义者 - 可读性是重点。如果你不这样做不认为它会使代码更具可读性,所以不要使用它,但我发现至少在某些时候情况恰恰相反。

The "contrived example" is how I would indent it, except that I would indent from the left margin, not based on where the ( or whatever is on the line above.

To the ternary detractors - readability is the point. If you don't think it makes for more readable code, don't use it. But I find the contrary to be the case at least some of the time.

ぶ宁プ宁ぶ 2024-07-15 12:33:21

我不使用它。 在我看来,这总是像试图节省空间并输入源代码,期望小源==更高效的编译代码。

我觉得它根本不可读,但这很大程度上是因为我从不使用它。

I don't use it. It always smelled to me like trying to save space and typing in source code with the expectation that small source == more efficient compiled code.

I don't find it readable at all, but much of that is because I just never use it.

卖梦商人 2024-07-15 12:33:21

伊姆兰,你的格式很漂亮。 但是,当嵌套两个以上时,三元运算符确实会变得不可读。 if-else 块可以为您提供额外级别的可理解嵌套。 除此之外,使用函数或表驱动编程。

Imran, you have formatted this beautifully. However, the ternary operator does tend to get unreadable as you nest more than two. an if-else block may give you an extra level of comprehensible nesting. Beyond that, use a function or table-driven programming.

近箐 2024-07-15 12:33:21
$foo = (isset($bar)) ? $bar : 'default';
$foo = (isset($bar)) ? $bar : 'default';
半夏半凉 2024-07-15 12:33:21

我个人只将它用于变量的赋值(在java中),例如:

String var = (obj == null) ? "not set" : obj.toString();

和(其他示例)当使用不允许空参数的函数时,例如:

String val; [...]
int var = (val == null) ? 0 : Integer.parseInt(val);

I personally only use it for an assignment of a variable (in java) for example :

String var = (obj == null) ? "not set" : obj.toString();

and (other example) when using function that doesn't allow null parameter such as :

String val; [...]
int var = (val == null) ? 0 : Integer.parseInt(val);
懷念過去 2024-07-15 12:33:21

我倾向于根本不使用三元运算符,因为我发现 if .. else 更具可读性。

I tend not to use the ternary operator at all as I find if .. else much more readable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文