How to avoid null checking in Java?

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

提交回复
热议问题