Why don't we have two nulls?

后端 未结 27 1088
孤独总比滥情好
孤独总比滥情好 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:45

    In haskell you can define something like this:

    data MaybeEither a b = Object a
                         | Unknown b
                         | Null
                           deriving Eq
    main = let x = Object 5 in
           if x == (Unknown [2]) then putStrLn ":-("
           else putStrLn ":-)"
    

    The idea being that Unknown values hold some data of type b that can transform them into known values (how you'd do that depends on the concrete types a and b).

    The observant reader will note that I'm just combining Maybe and Either into one data type :)

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

    In most programming languages null means "empty" or "undefined". "Unknown" on the other hand is something different. In essence "unknown" describes the state of the object. This state must have come from somewhere in your program.

    Have a look at the Null Object pattern. It may help you with what you are trying to achieve.

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

    In .net langages, you can use nullable types, which address this problem for value types.

    The problem remains, however, for reference types. Since there's no such thing as pointers in .net (at least in 'safe' blocks), "object? o" won't compile.

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

    If you are using .NET 3.0+ and need something else, you might try the Maybe Monad. You could create whatever "Maybe" types you need and, using LINQ syntax, process accordingly.

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

    Two nulls would be the wrongest answer around. If one null is not enough, you need infinity nulls.

    Null Could mean:

    • 'Uninitialized'
    • 'User didn't specify'
    • 'Not Applicable here, The color of a car before it has been painted'
    • 'Unity: This domain has zero bits of information.'
    • 'Empty: this correctly holds no data in this case, for example the last time the tires were rotated on a new car'
    • 'Multiple, Cascading nulls: for instance, the extension of a quantity price when no quantity may be specified times a quantity which wasn't specified by the user anyway'

    And your particular domain may need many other kinds of 'out of band' values. Really, these values are in the domain, and need to have a well defined meaning in each case. (ergo, infinity really is zero)

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

    Within PHP Strict you need to do an isset() check for set variables (or else it throws a warning)

    if(!isset($apple))
    {
        askForApple();
    }
    
    if(isset($apple) && empty($apple))
    {
        sulk();
    }
    else
    {
        eatApple();
    }
    
    0 讨论(0)
提交回复
热议问题