Why don't we have two nulls?

后端 未结 27 1089
孤独总比滥情好
孤独总比滥情好 2021-02-02 08:38

I\'ve often wondered why languages with a null representing \"no value\" don\'t differentiate between the passive \"I don\'t know what the value is\"

相关标签:
27条回答
  • 2021-02-02 08:53

    It's been tried: Visual Basic 6 had Nothing, Null, and Empty. And it led to such poor code, it featured at #12 in the legendary Thirteen Ways to Loathe VB article in Dr Dobbs.

    Use the Null Object pattern instead, as others have suggested.

    0 讨论(0)
  • 2021-02-02 08:53

    For me null represents lack of value, and I try to use it only to represent that. Of course you can give null as many meanings as you like, just like you can use 0 or -1 to represent errors instead of their numerical values. Giving various meanings to one representation could be ambiguous though, so I wouldn't recommend it.

    Your examples can be coded like apple.isRefused() or !apple.isValid() with little work; you should define beforehand what is an invalid apple anyway, so I don't see the gain of having more keywords.

    0 讨论(0)
  • 2021-02-02 08:56

    It would be easy enough to create a static constant indicating unknown, for the rare cases when you'd need such a thing.

    var apple = Apple.Unknown;
    while (apple == Apple.Unknown) {} // etc
    
    0 讨论(0)
  • 2021-02-02 08:57
    AppleInformation appleInfo;    
    while (appleInfo is null)
    {
        askForAppleInfo();
    }
    
    Apple apple = appleInfo.apple;
    if (apple is null)
    {
        sulk();
    }
    else
    {
        eatApple(apple);
    }
    

    First you check if you have the apple info, later you check if there is an apple or not. You don't need different native language support for that, just use the right classes.

    0 讨论(0)
  • 2021-02-02 08:58

    The Null type is a subtype of all reference types - you can use null instead of a reference to any type of object - which severely weakens the type system. It is considered one of the a historically bad idea by its creator, and only exists as checking whether an address is zero is easy to implement.

    0 讨论(0)
  • 2021-02-02 08:58

    As to why we don't have two nulls, is it down to the fact that, historically in C, NULL was a simple #define and not a distinct part of the language at all?

    0 讨论(0)
提交回复
热议问题