How to avoid null checking in Java?

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

    Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.

    My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.

    Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.

提交回复
热议问题