posted 9 years ago
True, when a variable is involved, it's possible to introduce a bug by mistakenly using = instead of ==, as in:
This is where you can get in trouble because on Line 4, instead of comparing the variable exists to true, it is instead assigned the value true and that becomes the value of the conditional expression for the if-statement. Basically, this particular bug will cause the body of the if-statement to always execute and the else part to never be executed, even if exists is false before Line 4 is executed. Line 11 eliminates the bug. However, if you make the same mistake and use = instead of == in this code:
you will know right away that something is wrong because this code won't compile because you can't assign a value to a method call. In either case, for consistency just don't compare a boolean expression with true or false.