Java: How to check for null pointers efficiently

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

    There is no vote for this one, but I use a slight variation of #2, like

    erStr += nullCheck (varName, String errMsg); // returns formatted error message
    

    Rationale: (1) I can loop over a bunch of arguments, (2) The nullCheck method is tucked away in a superclass and (3) at the end of the loop,

    if (erStr.length() > 0)
        // Send out complete error message to client
    else
        // do stuff with variables
    

    In the superclass method, your #3 looks nice, but I wouldn't throw an exception (what is the point, somebody has to handle it, and as a servlet container, tomcat will ignore it, so it might as well be this()) Regards, - M.S.

提交回复
热议问题