且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

没有NULL怎么办?

更新时间:2023-01-17 17:14:47

我不会直截了当地宣布可空类型是邪恶的,我会提出:大多数语言将可空性移植到所有类型上,而这两个概念确实应该正交.

Instead of outright declaring that nullable types are evil, I would posit: most languages graft nullability onto entire kinds of types, when the two concepts should really be orthogonal.

例如,所有非原始Java类型(以及所有C#引用类型)都可以为空.为什么?我们可以回去最终,但是我敢打赌,答案归结为很简单". Java语言没有内在的要求广泛的可空性. C ++参考提供了一个很好的示例,说明了如何在编译器级别消除null.当然,C ++的语法更加丑陋,Java明确试图减少这些语法,因此一些好的功能和坏的功能一起出现在了起步阶段.

For example, all non-primitive Java types (and all C# reference types) are nullable. Why? We can go back & forth, but ultimately I'll bet the answer comes down to "it was easy". There's nothing intrinsic to the Java language that demands widespread nullability. C++ references offered a fine example of how to exorcise nulls at the compiler level. Of course, C++ has a lot more ugly syntax that Java was explicitly trying to curtail, so some good features ended up on the cutting floor alongside the bad.

C#2.0中的可空值类型朝着正确的方向迈出了一步-将空性与无关的类型语义(或更糟糕的是,CLR实现细节)脱钩了,但是仍然缺少一种与引用类型相反的方法. (代码契约非常重要,但它们并没有像我们在这里讨论的那样嵌入在类型系统中.)

Nullable value types in C# 2.0 offered a step in the right direction -- decoupling nullability from unrelated type semantics, or worse, CLR implementation details -- but it's still missing a way to do the opposite with reference types. (Code contracts are great & all, but they're not embedded in the type system the way we're discussing here.)

大量功能性语言或其他晦涩的语言从一开始就使这些概念直截了当"……但是,如果它们被广泛使用,我们将不会进行讨论……

Plenty of functional or otherwise obscure languages got these concepts "straight" from the beginning...but if they were in widespread use, we wouldn't be having this discussion...

回答您的问题:禁止使用现代语言(批发)中的null就像所谓的十亿美元的错误"一样愚蠢.有一些有效的编程结构,其中的null值很不错:可选参数,任何类型的默认/后备计算,其中合并运算符会导致代码简洁,与关系数据库进行交互等.强迫自己使用前哨值,NaN等一种治愈"方法远不及这种疾病.

To answer your question: banning nulls from a modern language, wholesale, would be just as foolish as the so-called "billion dollar mistake." There are valid programming constructs where nulls are nice to have: optional parameters, any sort of default/fallback calculation where the coalesce operator leads to concise code, interaction with relational databases, etc. Forcing yourself to use sentinel values, NaN, etc would be a "cure" far worse than the disease.

也就是说,我会暂时同意报价单中表达的情感,只要我能根据自己的经历进行阐述即可:

That said, I'll tentatively agree with the sentiment expressed in the quote, so long as I may elaborate to fit my own experience:

  1. 需要null的情况少于大多数人的想法
  2. 将空值引入库或代码路径后,要摆脱空值比添加空值要困难得多. (因此,不要让初级程序员一时兴起!)
  3. 可空错误会随着生命周期的变化而扩展
  4. 与#3相关:早崩溃