How to avoid null checking in Java?

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

    If null-values are not allowed

    If your method is called externally, start with something like this:

    public void method(Object object) {
      if (object == null) {
        throw new IllegalArgumentException("...");
      }
    

    Then, in the rest of that method, you'll know that object is not null.

    If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

    Example:

    public String getFirst3Chars(String text) {
      return text.subString(0, 3);
    }
    

    However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

    If null is allowed

    This really depends. If find that I often do something like this:

    if (object == null) {
      // something
    } else {
      // something else
    }
    

    So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


    It's actually rare for me to use the idiom "if (object != null && ...".

    It may be easier to give you examples, if you show examples of where you typically use the idiom.

提交回复
热议问题