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.)

chills42
  • 14,201
  • 3
  • 42
  • 77

5 Answers5

32

Yes, it is exactly the same.

Yes, the latter is more readable.

j_random_hacker
  • 50,331
  • 10
  • 105
  • 169
  • 2
    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 Jan 07 '09 at 16:46
  • 1
    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 Jun 04 '10 at 10:15
5
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
  • 398,270
  • 210
  • 566
  • 880
1

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

arul
  • 13,998
  • 1
  • 57
  • 77
0

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

$IsTestActive = (boolean)$TestStateId;
faileN
  • 92
  • 1
0

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

(TestStateID == 1 ? true : false)

more readable.

Thomas Danecker
  • 4,635
  • 4
  • 32
  • 31