本文介绍了三元运算放大器&;保养的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序员只是喜欢一些运营商三元,尤其是嵌套的。更重要的是,他声称他们使代码更易于阅读和维护,因为它们可以适合于较少的线路。程序员乙认为,当ternaries嵌套可读性丢失,进而代码变得越来越难维护。

Programmer A just loves some ternary operators, especially nested ones. Better yet he claims that they make the code easier to read and maintain because they can be fit on fewer lines. Programmer B argues that readability is lost when ternaries are nested, and in turn the code becomes harder to maintain.

看看下面的块:

private int MyFunction(bool condA, bool condB)
{
  // Programmer A says:
  // Nested ternary --> This is easier to read and maintain because it is on one line.  Ternaries can be nested 4 or 5 deep and it is no problem.
  return condA ? condB ? 20 : -10 : -20;

  // Programmer B says:
  // Unwrapped --> This is more readable as it better describes the step by step evaluation of the conditions and their results.
  if (!condA) { return -20; }
  if (!condB) { return -10; }
  return 20;
}



编辑:??
是有更好的办法

Is there a better way?

推荐答案

我认为最好的办法是保持三元运算符,但加括号它

I think the best solution is to keep the ternary operator but add parenthesis to it

return condA ? ( condB ? 20 : -10 ) : -20;



否则可能会感到困惑容易。

otherwise it might get confused easily.

另外一个混合的方法也许是最好的,这里的三元运营商只对嵌套的最后一层发生。

Alternatively a hybrid approach might be best, where the ternary operators only occur on the last level of nesting.

if(condA)
{
    return condB ? 20 : -10;
} else {
    return -20;
}

这篇关于三元运算放大器&;保养的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 03:20