How to avoid null checking in Java?

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

    Common "problem" in Java indeed.

    First, my thoughts on this:

    I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..

    So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).

    The way I solve this problem is this:

    First, I follow this convention:

    1. All public methods / API always check its arguments for null
    2. All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
    3. The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...

    And finally, in the code, the first line of the public method goes like this:

    ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();
    

    Note that addParam() returns self, so that you can add more parameters to check.

    Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).

    void validate() throws ValidationException;
    

    The message will contain the following text if, for example, "plans" is null:

    "Illegal argument value null is encountered for parameter [plans]"

    As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).

    And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.

    This way, the code is clean, easy maintainable and readable.

提交回复
热议问题