空物体与物体空 [英] null objects vs. empty objects

查看:78
本文介绍了空物体与物体空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[这是最佳实践的结果:如果函数返回null或空对象?,但我想是很一般。 ]

[ 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 NullReferenceExceptions 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.

在Martin Fowler的重构<在引进空对象模式/一>(第260)也可以是有帮助的。空对象响应一个真正的对象会的所有方法,但在某种程度上说,做正确的事。因此,而不是随时查询订单,看是否order.getDiscountPolicy()为NULL,确保订单在这些情况下,NullDiscountPolicy。这简化了控制逻辑。

The "Introduce Null Object" pattern in Martin Fowler's Refactoring (page 260) may also be helpful. A Null Object responds to all the methods a real object would, but in a way that "does the right thing". So rather than always check an Order to see if order.getDiscountPolicy() is NULL, make sure the Order has a NullDiscountPolicy in these cases. This streamlines the control logic.

这篇关于空物体与物体空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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