编程语言为什么有null?

编程语言为什么有null

  • 一、null是谁发明的?
  • 二、我所理解的null存在的意义
  • References

色即是空,空即是色

色不异空,空不异色 —— 《心经》

千百年来,常有人拿这句话调侃和尚看见女色不断默念此经,以达到两眼空空的境界,连《西游记》里的女儿国一集都有这个桥段,可这唐玄奘法师,哪能两眼空空呢?如果你血气方刚,那么坦率承认和表达袒露眼前人的美,是空;如果你参悟大道,如庄子一般感悟到,天地有大美而不言,人的美丑掺杂着主观判断,也是空。

回到计算机世界,开始悟“空”。

一、null是谁发明的?

Java写业务代码时,如果时间匆忙,我经常忘记做null值的特例判断,这给我带来了不少的问题和麻烦,这令人又爱又恨的null值,究竟从何而来?

不像中文,中文的字词大多已经创造好,但英文这种表音文字,是有可能随时随地用字母造一个新词的。因此,null这个单词是否诞生于计算机发明之前?答案是肯定的。[1]

托尼·霍尔(Tony Hoare),编程世界中,null的创造者,也是快排算法(Quick Sort)的发明人,但身处历史洪流中的人物总有局限性,他在2009年的Qcon技术会议上,发表了一篇名为 NULL: The Billion Dollar Mistake 的演讲[2]

I call it my billion-dollar mistake…At that time, I was designing the first comprehensive type system for references in an object-oriented language. My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler.But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
– Tony Hoare, inventor of ALGOL W.

不过,也有人说,null的概念并不是由霍尔博士发明的,也许在机器语言程序员将指针指向0时,编程世界里,这个概念就诞生了。

With all due respect to Dr Hoare, I call hubris. Machine-language programmers invented the null reference the first time they set a pointer to zero. – Steven A. Lowe Nov 11, 2010 at 6:39

—— 来自StackOverflow的一条评论[3]

但也有编程语言是没有null这个概念的,如Haskell,这是门函数式编程语言,但我对函数式编程不懂。

Some programming languages (mostly functional programming languages like Haskell) don’t support the concept of null. Instead, they use the Maybe/Optional Pattern to represent the ‘absence of a value’. The compiler ensures that the ‘no value’ case is handled explicitly. Hence, null pointer errors cannot occur.[4]

二、我所理解的null存在的意义

集合里,空集(empty set)并不等于数字0,但空集是一个重要的概念,计算机中的null,也可以此类比,死亡,是宇宙的尽头,null,是编程语言的尽头,这里空无一物,没有给你分配的内存,不要再往下走了。就目前为止,我只能从这个层面出发,去理解为什么有null

0能够表达非数值概念的空无,无法表达数值的空无。

null能够表达一切范围的空无,却不能表达自己的空无。这个矛盾,源于自指。

References

[1] ‘null’ in dictionary

[2] Null References: The Billion Dollar Mistake

[3] what is the purpose of null?

[4] A quick and thorough guide to ‘null’: what it is, and how you should use it

[5] If null is a billion dollar mistake, what is the solution to represent a non-initialized object?

[6] NULL: The Billion Dollar Mistake

你可能感兴趣的:(开发语言)