Wednesday, November 08, 2006

Java code snippets

So I started a new contract recently and as I spent the first week reading documentation and going over the existing application's code, I saw something that wasn't wrong but it did catch my attention.

Do you see the difference between these two conditions?

String country = form.getCountry();
if (country.equals(Constants.USA)) {...}

and...

String country = form.getCountry();
if (Constants.USA.equals(country)) {...}


The first sample is safer as you do not run the risk of getting a NullPointerException.

It's always nice to have the time to simply read other people's code and pick up on these kind of small things. One reason why code reviews are so valuable when done correctly (unfortunately it's hard to justify the cost to the organization and most places don't provision for it).

4 comments:

Anonymous said...

The first sample is safer as you do not run the risk of getting a NullPointerException.

Imho second is safer. Constants.USA is defined allways, while form.getCountry() can be null.

So Constants.USA.equals(form.getCountry) is better.

Jacob Hookom said...

don't you mean the second sample?

Billy Bob Bain said...

I think you have that backwards. If country is null, the 1st one will NPE.

Wayland Chan said...

Yes, you're correct. I meant to say the second one.