默认情况下,面向对象编程语言中的引用是否应为空? [英] Should References in Object-Oriented Programming Languages be Non-Nullable by Default?

查看:82
本文介绍了默认情况下,面向对象编程语言中的引用是否应为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空指针被描述为"十亿美元的错误.某些语言具有无法为null值分配的引用类型.

Null pointers have been described as the "billion dollar mistake". Some languages have reference types which can't be assigned the null value.

我想知道在设计一种新的面向对象的语言时,默认行为是否应该用于引用,以防止被分配为null.然后可以使用的特殊版本来覆盖此行为.例如:

I wonder if in designing a new object-oriented language whether the default behavior should be for references to prevent being assigned null. A special version of the could then be used to override this behavior. For example:

MyClass notNullable = new MyClass();
notNullable = null; // Error!
// a la C#, where "T?" means "Nullable<T>"
MyClass? nullable = new MyClass();
nullable = null; // Allowed

所以我的问题是,是否有任何理由不以新的编程语言来执行此操作?

So my question is, is there any reason not to do this in a new programming language?

我想添加

I wanted to add that a recent comment on my blog pointed out that non-nullable types have a particular problem whenb used in Arrays. I also want to thank everyone for their useful insights. It is very helpful, sorry I could only choose one answer.

推荐答案

默认情况下,我看到的主要障碍是非空引用类型,这是编程社区中的某些人更喜欢使用创建集使用模式:

The main obstruction I see to non-nullable reference types by default is that some portion of the programming community prefers the create-set-use pattern:

x = new Foo()
x.Prop <- someInitValue
x.DoSomething()

重载的构造函数:

x = new Foo(someInitValue)
x.DoSomething()

,这使API设计人员可以绑定实例变量的初始值,否则该实例变量可能为null.

and this leaves the API designer in a bind with regards to the initial value of instance variables that might otherwise be null.

当然,就像"null"本身一样,create-set-use模式本身也会创建许多无意义的对象状态并防止有用的不变量,因此,摆脱这种情况实际上是一种祝福而不是诅咒.但是,它确实以许多人不熟悉的方式影响了一些API设计,因此这并不是一件容易的事.

Of course, like 'null' itself, the create-set-use pattern itself creates lots of meaningless object states and prevents useful invariants, so being rid of this is really a blessing rather than a curse. However it does affect a bit of API design in a way that many people will be unfamiliar with, so it's not something to do lightly.

但是总的来说,是的,如果发生了一场巨大的灾难,摧毁了所有现有的语言和编译器,人们只能希望我们重建时不会重蹈覆辙.可空性是例外,而不是规则!

But overall, yes, if there is a great cataclysm that destroys all existing languages and compilers, one can only hope that when we rebuild we will not repeat this particular mistake. Nullability is the exception, not the rule!

这篇关于默认情况下,面向对象编程语言中的引用是否应为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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