How to avoid null checking in Java?

后端 未结 30 3270
失恋的感觉
失恋的感觉 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:28

    In addition to using assert you can use the following:

    if (someobject == null) {
        // Handle null here then move on.
    }
    

    This is slightly better than:

    if (someobject != null) {
        .....
        .....
    
    
    
        .....
    }
    

提交回复
热议问题