The Coded One

programming, algorithms, discrete math, open-source

Posts Tagged ‘conditional statements

Writing Better Conditional Statements

leave a comment »

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.

Written by Mark Basmayor

February 28, 2009 at 4:49 pm

Follow

Get every new post delivered to your Inbox.