Posts Tagged ‘conditional statements’
Writing Better Conditional Statements
1. Use 1 == foo instead of foo == 1. Srsly.
At a glance, you might think that the following statements are the same as dictated by logic and the property of commutativity.
if( foo == 1 ) {
...
and
if( 1 == foo ) {
...
Well logically yes, but in a pragmatic point of view, the second one is better because it makes the compiler barf an error whenever you’re in a zombie programming mode and you write = (which assigns the value to the variable instead of checking for equality) in lieu of ==.
I just can’t imagine how much time I spent debugging before, only to find out that I missed a single character.
2. Proper use of .equals
First of all, when comparing strings, always use .equals. The == operator compares references and not values.
Now, if you're checking for a "" or a null string, use the following form:
if( "".equals( foo ) ) {
...
This way, you do not get a Null Pointer Exception whenever the variable is null.