If we define a boolean variable, say:
bool xyz;
then when we have to do some kind of a comparison we may do this as follows:
if(xyz == true)
When I used to be a new programmer, I used to always do this as follows:
if(true == xyz)
I think the way I did it is more robust and less error prone because you can by mistake do as follows:
if(xyz = true) //Single = instead of ==
The problem with my approach is that the code readability is affected and most people hate to see code like this. Instead, I started doing what normal people would do but making sure that I always use '==' and not '='.
Now some of you may be thinking why not:
if(xyz)
True, in case of Boolean this is a simplest way to do it and I had personally no problem with it until recently. While reviewing some code, I noticed that an engineer had changed a piece of code from:
if(xyz == true) to if(xyz)
Initially I thought that it may be that he did not like the '==' as its redundant. So when I checked his other code, I realised that he may have done this for a reason. Executing his code in the debug mode worked fine. So I changed:
if(xyz) back to if(xyz == true) and lo and behold, the test started to fail.
Putting a breakpoint I can see that while on the statement:
if(xyz == true)
the debugger shows xyz is 'true' but the comparison fails.
As usual digging into the problem further, I found that in one of the constructors, xyz was not initialised and the default garbage value appeared to show it as 'true'.
So its again got me into thinking that it may be better to write if(xyz == true) instead of if(xyz) as it may help in catching uninitialised variables. The best thing of course would be to make sure all variables in the class, whether public, protected or private are initialised.
Opinions welcome!