views:

399

answers:

6

I found this statement is some old code and it took me a second to figure out...

IsTestActive = (TestStateID == 1 ? true : false);

Please correct me if I'm wrong but isn't this the same as this one?:

IsTestActive = (TestStateID == 1);

If it is, why would you ever want to use the first? Which one is more readable? (I think the latter, but I'd like to see what others think.)

+31  A: 

Yes, it is exactly the same.

Yes, the latter is more readable.

j_random_hacker
agreed - the latter
annakata
Ok, good too see that others agree. I couldn't understand why that was there...
chills42
I've only seen the former used by 2 types of people: those who lack a fundamental understanding of boolean logic, or those that think the ternary operator is really cool.
John Kraft
definitely the latter one.
dr. evil
The former would theoretically have a minute perf hit, though if you're caring about that level of performance then I suspect you have bigger problems...
Dan Puzey
+1  A: 

No, there's no practical reason for using the first version, world isn't perfect, and neither are programmers.

arul
Love that site, always nice to see new ways not to do things...
chills42
A: 

I must admit I'd never seen nor used the latter one, only the former. But thanks for the learning tip!

Ian Devlin
+4  A: 
IsTestActive = (TestStateID == 1);

is definitely more readable.

You could make a case for defining a constant

ACTIVE = 1

then replacing the boolean variable IsTestActive with

(TestStateID == ACTIVE)

The way the code is now, the state of the boolean IsTestActive will be erroneous if the state of TestStateID changes without updating the boolean. Bypassing the boolean and testing the real source of the information you're after will remove the possibility of this error.

Bill the Lizard
good point, I hate magic integers - but I assume the OP was just posting example code
annakata
That may be, but I do see a lot of people using temp variables like this in production code.
Bill the Lizard
A: 

Readability depends on where you use this construct. I often find something like

(TestStateID == 1 ? true : false)

more readable.

Thomas Danecker
A: 

Well, I don't know about other languages, but in PHP it's even more easy, using type-casting:

$IsTestActive = (boolean)$TestStateId;
faileN