Best way to check for null values in Java?

后端 未结 16 1091
傲寒
傲寒 2020-12-04 16:30

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.

What is the best way to go abou

相关标签:
16条回答
  • 2020-12-04 17:17

    Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.

    0 讨论(0)
  • 2020-12-04 17:17

    Simple one line Code to check for null :

    namVar == null ? codTdoForNul() : codTdoForFul();
    
    0 讨论(0)
  • 2020-12-04 17:20

    If you control the API being called, consider using Guava's Optional class

    More info here. Change your method to return an Optional<Boolean> instead of a Boolean.

    This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional

    0 讨论(0)
  • 2020-12-04 17:23

    Your last proposal is the best.

    if (foo != null && foo.bar()) {
        etc...
    }
    

    Because:

    1. It is easier to read.
    2. It is safe : foo.bar() will never be executed if foo == null.
    3. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
    4. It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).
    0 讨论(0)
提交回复
热议问题