Java: How to check for null pointers efficiently

前端 未结 14 1783
清歌不尽
清歌不尽 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:55

    In my opinion, there are three issues with the third method:

    1. The intent is unclear to the casual reader.
    2. Even though you have line number information, line numbers change. In a real production system, knowing that there was a problem in SomeClass at line 100 doesn't give you all the info you need. You also need to know the revision of the file in question and be able to get to that revision. All in all, a lot of hassle for what appears to be very little benefit.
    3. It is not at all clear why you think the call to arg.getClass can be optimized away. It is a native method. Unless HotSpot is coded to have specific knowledge of the method for this exact eventuality, it'll probably leave the call alone since it can't know about any potential side-effects of the C code that gets called.

    My preference is to use #1 whenever I feel there's a need for a null check. Having the variable name in the error message is great for quickly figuring out what exactly has gone wrong.

    P.S. I don't think that optimizing the number of tokens in the source file is a very useful criterion.

提交回复
热议问题