What's the point of Guava checkNotNull

后端 未结 3 1726
甜味超标
甜味超标 2020-12-13 07:58

I\'m pretty new to Guava (let\'s be honest, I\'m not \"pretty new\", I\'m a complete rookie on that subject) and so I decided to go through some documentation and got quite

3条回答
  •  执念已碎
    2020-12-13 08:35

    myObject.getAnything(); (which might cause a NullPointerException if myObject is null)

    No... it will throw NPE whenever myObject == null. In Java, there's no chance of calling a method with null receiver (a theoretical exception are static methods, but they can and should be always called without any object).


    I should use checkNotNull(myObject).getAnything();

    No you should not. This would be rather redundant (Update).

    You should use checkNotNull in order to fail fast. Without it, you may pass an illegal null to another method, which passes it further, and so on and so on, where it finally fails. Then you can need some good luck to find out that actually the very first method should have refused null.


    The answer by yshavit mentions an important point: Passing an illegal value is bad, but storing it and passing it later is even worse.

    Update

    Actually,

     checkNotNull(myObject).getAnything()
    

    makes sense, too, as you clearly express your intent to not accept any nulls. Without it, someone could think that you forgot the check and convert it into something like

     myObject != null ? myObject.getAnything() : somethingElse
    

    OTOH, I don't think the check is worth the verbosity. In a better language, the type system would consider nullability and give us some semantic sugar like

     myObject!!.getAnything()                    // checkNotNull
     myObject?.getAnything()                     // safe call else null
     myObject?.getAnything() ?: somethingElse    // safe call else somethingElse
    

    for nullable myObject, while the standard dot syntax would be allowed only when myObject is known to be non-null.

提交回复
热议问题