Setting a boolean value based on an integer
-
05-07-2019 - |
Question
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.)
Solution
Yes, it is exactly the same.
Yes, the latter is more readable.
OTHER TIPS
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.
No, there's no practical reason for using the first version, world isn't perfect, and neither are programmers.
Readability depends on where you use this construct. I often find something like
(TestStateID == 1 ? true : false)
more readable.
Well, I don't know about other languages, but in PHP it's even more easy, using type-casting:
$IsTestActive = (boolean)$TestStateId;