When should null values of Boolean be used?

前端 未结 14 2359
心在旅途
心在旅途 2020-12-04 07:32

Java boolean allows values of true and false while Boolean allows true, false, and null. I have

14条回答
  •  自闭症患者
    2020-12-04 07:44

    ANSWER TO OWN QUESTION: I thought it would be useful to answer my own question as I have learnt a lot from the answers. This answer is intended to help those - like me - who do not have a complete understanding of the issues. If I use incorrect language please correct me.

    • The null "value" is not a value and is fundamentally different from true and false. It is the absence of a pointer to objects. Therefore to think that Boolean is 3-valued is fundamentally wrong
    • The syntax for Boolean is abbreviated and conceals the fact that the reference points to Objects:

      Boolean a = true;

    conceals the fact that true is an object. Other equivalent assignments might be:

    Boolean a = Boolean.TRUE;
    

    or

    Boolean a = new Boolean(true);
    
    • The abbreviated syntax

      if (a) ...

    is different from most other assignments and conceals the fact that a might be an object reference or a primitive. If an object it is necessary to test for null to avoid NPE. For me it is psychologically easier to remember this if there is an equality test:

    if (a == true) ...

    where we might be prompted to test for null. So the shortened form is only safe when a is a primitive.

    For myself I now have the recommendations:

    • Never use null for a 3-valued logic. Only use true and false.
    • NEVER return Boolean from a method as it could be null. Only return boolean.
    • Only use Boolean for wrapping elements in containers, or arguments to methods where objects are required

提交回复
热议问题