Using true and false as the expressions in a condi

2019-06-15 01:40发布

I'm maintaining some code and have found the following pattern a lot:

var isMale = (row["Gender"].ToString() == "M") ? true : false;

instead of this:

var isMale = (row["Gender"].ToString() == "M");

Is there any reason why anyone would do this? Does anyone think the former is more readable or clearer? Is there some sort of old C "gotcha" that this is a hold-over from?

9条回答
祖国的老花朵
2楼-- · 2019-06-15 02:09

A valid reason? No.

It's usually produced by people who don't really understand that a condition is also in itself an expression, producing a boolean result. In particular, people schooled on a language where this isn't the case, such as many variants of BASIC.

查看更多
3楼-- · 2019-06-15 02:13

I guess some people are not comfortable with assigning anything other that true or false to a boolean variable. Don't know why this is, but I have observed it quite a few times.

So, from that aspect it looks like:

set sarcasm on

bool isMale = (row["Gender"].ToString() == "M"); //BAAAAD

but

bool isMale = (row["Gender"].ToString() == "M") ? true : false; //BETTER

and

bool isMale;
if (row["Gender"].ToString() == "M") 
    isMale = true;
else 
    isMale = false;   // BEST!

set sarcasm off

Luckily Resharper makes short work of all these anti-patterns.

查看更多
淡お忘
4楼-- · 2019-06-15 02:16

The 2nd way sure makes the most sense and I think it's easier to read.

The 2nd way is a bit more clever. I wouldn't put it past me to do something like you are finding if I was churning out code on a Friday afternoon and my brain was already gone for the weekend :-)

查看更多
狗以群分
5楼-- · 2019-06-15 02:17

If you can't trust: (row["Gender"].ToString() == "M") to product true or false correctly, then you probably can't really trust: (row["Gender"].ToString() == "M") ? true : false; either. To be sure, you undoubtedly need to repeat it at least a few more times:

(row["Gender"].ToString() == "M") ? true : false ? true : false ? true : false;

Then again, maybe you can't trust a combination of == and ?: by themselves either -- to be really sure, you probably need at least a bit more redundancy:

if ((row["Gender"].ToString() == "M") ? true : false ? true : false ? true : false == true)
    isMale = true == true;
else
    isMale = false != false;

Hmm...maybe I stayed up too late last night... :-)

查看更多
神经病院院长
6楼-- · 2019-06-15 02:18

The

if (somebool) return true;
else return false;

"pattern" gets laughed at pretty much everywhere I've ever worked. No reason to do it in my opinion.

查看更多
老娘就宠你
7楼-- · 2019-06-15 02:19

Definitely redundant. Could be a leftover practice from another programming language/environment that the original developer was retaining. I could also potentially see a developer viewing the first line as being more readable in that he/she can quickly see that it's setting a boolean when skimming through the code.

查看更多
登录 后发表回答