开发者

Java equals() ordering

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?


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.


is this just really poor code?

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


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") ) {
    ...


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.


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


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.equals(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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜