在这种情况下,多个条件运算符是一个好主意? [英] Are multiple conditional operators in this situation a good idea?

查看:132
本文介绍了在这种情况下,多个条件运算符是一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看到code上的维基百科有条件运营商的文章:

I just saw this block of code on the Wikipedia article on conditional operators:

Vehicle new_vehicle = arg == 'B' ? bus      :
                      arg == 'A' ? airplane :
                      arg == 'T' ? train    :
                      arg == 'C' ? car      :
                      arg == 'H' ? horse    :
                      feet;

我已经改变了code一点点,但这个想法是一样的。你会发现这种使用条件运算符可以接受的?它比更加简洁的如果 - 其他施工,同时使用开关肯定会开辟一个全新的集对于错误的机会(下跌得来的人?)。此外,如果 - 其他开关不能作为R值,所以你必须先创建变量,将其初始化,然后分配是必要的。

I've changed the code a little, but the idea is the same. Would you find this use of the conditional operator acceptable? It's much more concise than the if-else construct, and using a switch would definitely open up a whole new set of opportunities for bugs (fall-throughs anyone?). Also, if-elses and switch can't be used as R-values, so you'd have to create the variable first, initialize it and then assign as necessary.

一,我真的很喜欢这一点,但我不知道别人怎么想。

I for one really like this, but I'm wondering what others think.

但格式是至关重要的。

编辑:我还是很喜欢这一点。但我理解那些谁说开关语句为这个制造。好吧,也许如此。但是,如果条件函数调用返回布尔?或者一百万其他的东西你不能开机。

I still like this. But I understand those who say "the switch statement was made for this". OK, maybe so. But what if the conditions are function calls that return bool? Or a million other things you can't switch on.

您交换机的恋人真的想说服我,一个巨大的如果 - 其他链比较好?是的,程序员谁不知道如何使用条件运算符不会明白这一点。他们应该学会如何使用它。这不是神秘的。

Are you switch lovers really trying to convince me that a huge if-else chain is better? Yes, programmers who don't know how to use the conditional operator will not understand this. They should learn how to use it. It's not arcane.

推荐答案

我已经使用这个类型的建筑很多次。只要它是格式良好的(即不是所有在同一行,使之成为不可读),我不认为它有问题。

I have used this type of construction many times. As long as it's formatted nicely (i.e. not all on one line, making it unreadable), I don't see a problem with it.

这篇关于在这种情况下,多个条件运算符是一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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