How to avoid null checking in Java?

后端 未结 30 3205
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
相关标签:
30条回答
  • 2020-11-21 05:19

    Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

    The example given by Alex Miller looks like this:

    public String getPostcode(Person person) {  
      return person?.getAddress()?.getPostcode();  
    }  
    

    The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.


    Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.


    Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.

    0 讨论(0)
  • 2020-11-21 05:19

    Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

    When the exception is thrown, examine the stack trace and work through the bug.

    0 讨论(0)
  • 2020-11-21 05:21

    Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

    Example:

    String foo;
    ...
    if( StringUtils.isBlank( foo ) ) {
       ///do something
    }
    

    or (depending on what you need to check):

    String foo;
    ...
    if( StringUtils.isEmpty( foo ) ) {
       ///do something
    }
    

    The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

    Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

    public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
        Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
        return read(new StringReader(xml), true, validationEventHandler);
    }
    

    And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

    Example on how to use this static classf from spring(org.springframework.util.Assert)

    Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
    
    0 讨论(0)
  • 2020-11-21 05:23
    • If you consider an object should not be null (or it is a bug) use an assert.
    • If your method doesn't accept null params say it in the javadoc and use an assert.

    You have to check for object != null only if you want to handle the case where the object may be null...

    There is a proposal to add new annotations in Java7 to help with null / notnull params: http://tech.puredanger.com/java7/#jsr308

    0 讨论(0)
  • 2020-11-21 05:23

    Common "problem" in Java indeed.

    First, my thoughts on this:

    I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..

    So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).

    The way I solve this problem is this:

    First, I follow this convention:

    1. All public methods / API always check its arguments for null
    2. All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
    3. The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...

    And finally, in the code, the first line of the public method goes like this:

    ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();
    

    Note that addParam() returns self, so that you can add more parameters to check.

    Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).

    void validate() throws ValidationException;
    

    The message will contain the following text if, for example, "plans" is null:

    "Illegal argument value null is encountered for parameter [plans]"

    As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).

    And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.

    This way, the code is clean, easy maintainable and readable.

    0 讨论(0)
  • 2020-11-21 05:23
    public static <T> T ifNull(T toCheck, T ifNull) {
        if (toCheck == null) {
               return ifNull;
        }
        return toCheck;
    }
    
    0 讨论(0)
提交回复
热议问题