Java: How to check for null pointers efficiently

前端 未结 14 1758
清歌不尽
清歌不尽 2020-12-03 01:17

There are some patterns for checking whether a parameter to a method has been given a null value.

First, the classic one. It is common in self-made code

14条回答
  •  遥遥无期
    2020-12-03 01:54

    First method. I would never do the second or the third method, not unless they are implemented efficiently by the underlying JVM. Otherwise, those two are just prime examples of premature optimization (with the third having a possible performance penalty - you don't want to be dealing and accessing class meta-data in general access points.)

    The problem with NPEs is that they are things that cross-cut many aspects of programming (and my aspects, I mean something deeper and more profound that AOP). It is a language design problem (not saying that the language is bad, but that it is one fundamental short-coming... of any language that allows null pointers or references.)

    As such, it is best to simply deal with it explicitly as in the first method. All other methods are (failed) attempts to simplify a model of operations, an unavoidable complexity that exists on the underlying programming model.

    It is a bullet that we cannot avoid to bite. Deal with it explicitly as it is - in the general case that is - the less painful down the road.

提交回复
热议问题