为什么我们没有两个空值? [英] Why don't we have two nulls?

查看:54
本文介绍了为什么我们没有两个空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想知道为什么带有 null 表示 无值" 的语言不区分被动 我不知道什么是价值是,而更自信的没有价值.".

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" and the more assertive "There is no value.".

有几种情况我希望区分这两者(尤其是在处理用户输入和数据库时).

There have been several cases where I'd have liked to differentiate between the two (especially when working with user-input and databases).

我想象如下,我们将两个状态命名为 unknownnull:

I imagine the following, where we name the two states unknown and null:

var apple;

while (apple is unknown)
{
    askForApple();
}

if (apple is null)
{
    sulk();
}
else
{
    eatApple(apple);
}

显然,我们可以通过在其他地方手动存储状态来摆脱它,但我们也可以对空值这样做.

Obviously, we can get away without it by manually storing the state somwhere else, but we can do that for nulls too.

那么,如果我们可以有一个 null,为什么我们不能有两个?

So, if we can have one null, why can't we have two?

推荐答案

在我的编程中,我最近采用了区分语言空值"和域空值"的做法.

In my programming, I recently adopted the practice of differentiating "language null" and "domain null".

语言空值"是编程语言提供的特殊值,表示一个变量没有值".在数据结构、参数列表和返回值中需要它作为虚拟值.

The "language null" is the special value that is provided by the programming language to express that a variable has "no value". It is needed as dummy value in data structures, parameter lists, and return values.

域空值"是实现NullObject 设计模式的任意数量的对象.实际上,对于每个域上下文,您都有一个不同的域 null.

The "domain null" is any number of objects that implement the NullObject design pattern. Actually, you have one distinct domain null for each domain context.

程序员使用 null 语言作为一个包罗万象的域 null 是相当普遍的,但我发现它往往使代码更加程序化(更少面向对象)并且更难以辨别意图.

It is fairly common for programmers to use the language null as a catch-all domain null, but I have found that it tends to make code more procedural (less object oriented) and the intent harder to discern.

每次想要空值时,问问自己:这是语言空值还是域空值?

Every time to want a null, ask yourself: is that a language null, or a domain null?

这篇关于为什么我们没有两个空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆