Reverse Conditionals

I have made this mistake countless times in Java where I type “if (variable=1)” instead of “if (variable==1)”. The former will always return true since there is no error assigning the value “1” to the variable (assuming correct variable type), whereas the latter depends on whether the variable contains the value “1”.

To prevent such errors from cropping up in your code in your conditions, you can make use of the non-intuitive reverse conditionals. To modify my example above using reverse conditionals, I will type “if (1=variable)” and “if (1==variable)” instead. In this case, the former will immediately throw up an error upon compilation since it is not possible to assign a value to a literal in this case.

Leave a Reply

Your email address will not be published. Required fields are marked *