问题描述
[这是,但我想是很一般。 ]
[ This is a result of Best Practice: Should functions return null or an empty object? but I'm trying to be very general. ]
在很多传统的(嗯...生产)的C ++代码,我所看到的,有写的很多的倾向中的 NULL 的(或类似)进行检查,以测试指针。许多这些获得加时,附近的一个发布周期的末尾增加了的 NULL 的-check提供了一个快速解决所造成的指针引用崩溃 - 并没有很多时间来调查
In a lot of legacy (um...production) C++ code that I've seen, there is a tendency to write a lot of NULL (or similar) checks to test pointers. Many of these get added near the end of a release cycle when adding a NULL-check provides a quick fix to a crash caused by the pointer dereference--and there isn't a lot of time to investigate.
要解决这个问题,我开始写代码,花了(常量
)的参考参数,而不是(多)使指针的更常用的技术。没有指针,没有欲望检查的 NULL 的(忽略实际上有一个空引用角落的情况下)。
To combat this, I started to write code that took a (const
) reference parameter instead of the (much) more common technique of passing a pointer. No pointer, no desire to check for NULL (ignoring the corner case of actually having a null reference).
在C#中,相同的C ++ 问题存在:要检查空
每一个未知的参考欲望( ArgumentNullException
),并迅速解决的NullReferenceException
S按添加空
支票。
In C#, the same C++ "problem" is present: the desire to check every unknown reference against null
(ArgumentNullException
) and to quickly fix NullReferenceException
s by adding a null
check.
这似乎我,为防止这一方法是使用空对象(的String.Empty
, EventArgs.Empty )代替。另一个办法是抛出一个异常,而不是返回
空
。
It seems to me, one way to prevent this is to avoid null objects in the first place by using empty objects (
String.Empty
, EventArgs.Empty
) instead. Another would be to throw an exception rather than return null
.
我刚开始学习F#,但它似乎有在该环境少得多空对象。因此,也许你真的没有有很多
空
引用的左右浮动?
I'm just starting to learn F#, but it appears there are far fewer null objects in that enviroment. So maybe you don't really have to have a lot of
null
references floating around?
是我吠叫错了吗?
推荐答案
我往往很可疑的代码有很多空值,并尝试重构他们离开那里可能有例外,空收藏, 等等。
I tend to be dubious of code with lots of NULLs, and try to refactor them away where possible with exceptions, empty collections, and so on.
这篇关于空物体与物体空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!