How to avoid null checking in Java?

后端 未结 30 3194
失恋的感觉
失恋的感觉 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.

提交回复
热议问题