How to avoid null checking in Java?

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

    Ultimately, the only way to completely solve this problem is by using a different programming language:

    • In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
    • In Nice, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.

提交回复
热议问题