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).
Wednesday, November 08, 2006
Subscribe to:
Post Comments (Atom)
4 comments:
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.
don't you mean the second sample?
I think you have that backwards. If country is null, the 1st one will NPE.
Yes, you're correct. I meant to say the second one.
Post a Comment