Java equals() ordering

后端 未结 6 912
执念已碎
执念已碎 2021-01-12 02:55

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

相关标签:
6条回答
  • 2021-01-12 03:22

    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.

    0 讨论(0)
  • 2021-01-12 03:22

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

    0 讨论(0)
  • 2021-01-12 03:24

    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") ) {
        ...
    
    0 讨论(0)
  • 2021-01-12 03:29

    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.

    0 讨论(0)
  • 2021-01-12 03:34

    is this just really poor code?

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

    0 讨论(0)
  • 2021-01-12 03:34

    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.

    0 讨论(0)
提交回复
热议问题