tags:

views:

139

answers:

6

If I try to do a .equals() on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to some constant string, can I do the following:

MY_CONSTANT_STRING.equals(aStringVariable)

I know it will work, but is this just really poor code?

+11  A: 

This is a standard Java idiom jokingly called a Yoda condition.

Personally I prefer to handle the null case explicitly, but the Yoda way is used a lot and any experienced Java programmer should be able to understand what is going on immediately. It's fine to use.

Mark Byers
+1 cause I've just learnt Master Yoda's Conditions thanks to this answer.http://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined/2430307#2430307
Fernando
+4  A: 

What you've got is fine. It's even possible to use a String literal.

if( "value".equals(variable) ) {
    ...

If you don't like that, you can always explicitly check for null and equality, and combine the two checks with &&. The short circuiting of the operator will make sure you never get a NPE.

if( (variable != null) && variable.equals("value") ) {
    ...
Bill the Lizard
The parentheses around variable!=null are optional should you wish to reduce the clutter.
Steve Kuo
+5  A: 

is this just really poor code?

No, this is the way many people would code the statement to avoid NPE.

camickr
A: 

Nope, it's usually done to avoid NPE. However, I usually prefer to do explicit check for null.

CoolBeans
+1  A: 

I would keep the "CONSTANT.equals(possibleNull)" code without the null test only if it is a normal condition that the variable could be null - for instance because it just came out of a property map.

Similarly you can get away with not checking for null in instanceof-checks - like:

Food dinner = map.get("dinner");
if (dinner instanceof Soup) {
      ((Soup)blah).eat();
}  // We don't care if it is a Fish or null

But if you really did not expect null, you should explicitly check for that in a separate if-test, and handle it appropriately. It's generally better to catch such data errors early rather than later.

Stian Soiland-Reyes
A: 

If you are concerned about the quality of your code, write a helper class that takes care of equality test:

public class ObjectHelper {
    public static boolean testEquality(Object o1, Object o2) {
        if (o1 == null && o2 == null) return true;
        if (o1 == null) return false;
        return o1.equalts(o2);
    }
}

Then use it like this:

if (ObjectHelper.testEquality(aStringVariable, My_CONSTANT_STRING))

Your so-called constant MIGHT stop being constant. It might be read from a configuration file some time in the future.

houman001