返回 null 还是空集合更好?

发布于 2024-10-06 15:36:10 字数 116 浏览 0 评论 0原文

假设我有一个返回数组、列表或其他集合的方法。如果内部出现问题或者根本没有数据可返回,那么返回 null 还是返回长度(计数)等于 0 的数组(列表等)更好?

事实上它很重要,还是只是开发人员偏好的问题?

Suppose I have a method that returns an array or list or some other collection. If something goes wrong inside or when there is simply no data to return, what is better - to return null or to return array (list, etc.) that has length (count) equal to 0?

In fact is it important, or it is just a matter of developer's preferences?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

暖树树初阳… 2024-10-13 15:36:10

最好返回一个空集合。这样,当有人像这样调用该函数时:

foreach(var i in items)
{

}

它不会向他们抛出空引用异常。

从技术上讲,您可能会争论空与 null 的意思,但实际上很多人(有时包括我自己)忘记了防御性,并且在使用对象之前不检查该对象是否为 null 。它正在发挥其他人认为将会发生的事情,这意味着更少的错误和更少的愤怒的用户。

It's better to return an empty collection. This way when someone calls the function like so:

foreach(var i in items)
{

}

it doesn't throw a null reference exception on them.

Technically, you could argue empty vs. null means, but in reality a lot of people (myself included at times) forget to be defensive and don't check to see if the object is null before using it. It's playing into what other people assume is going to happen, which means less bugs and less angry users.

最笨的告白 2024-10-13 15:36:10

如果您返回空集合而不是 null,您的迭代代码将会容易得多。

但是,区分空集合和无数据集合可能很重要,因此这取决于实际类型的语义。

Your iteration code will be a lot easier if you return empty collections instead of null.

However, it may be important to distinguish between an empty collection and no collection of data, so it depends on the semantic of the actual type.

↘人皮目录ツ 2024-10-13 15:36:10

如果出现“问题”,您应该抛出异常。如果没有数据可返回,则返回空集合。当开发人员请求一个项目列表并且恰好没有返回的项目时,通常不应对 NullReferenceException 感到惊讶。

If something "goes wrong" you should throw an exception. If there is no data to return, return an empty collection. Developers generally should not be surprised with a NullReferenceException when they ask for a list of items and there just happen to be none to return.

呆萌少年 2024-10-13 15:36:10

我可以看到这两种情况都会发生。最终,数组或集合具有更大的占用空间,但“更安全”,因为如果在将来的 foreach/迭代中使用结果,则结果将跳过代码块并且不会以空对象异常结束。

I could see this going either way. Ultimately an array or collection with have a larger footprint, but is "Safer" in the sense that if the result is being used in future foreach/iterations the result will skip over the code block and not end up with a null object exception.

待天淡蓝洁白时 2024-10-13 15:36:10

嗯,nullempty 有两种不同的含义。空集合实际上意味着“这里什么都没有”,并且可能是有效的。基于空集合,您如何知道是否出现问题?

虽然它对于调用方法来说更安全,但这并不比返回 null 更好。良好的实践表明,您应该在对对象进行操作之前检查 null 。反正很便宜。

如果确实出了问题,为什么不能抛出异常呢?

Well, null and empty have two different meanings. An empty collection effectively means "nothing is here", and could be valid. How would you know if something went wrong based on an empty collection?

While it is safer for the calling method, that doesn't make it better than returning null. Good practice states you should check for null before doing operations on an object. It is cheap anyway.

If something truly went wrong, why cant you throw an exception?

满栀 2024-10-13 15:36:10

这确实是开发人员的偏好。

返回空列表

通常我会返回一个空列表,以便方法返回对象的接收者不需要检查 null 并避免任何可能的 NullReferenceException

因此,任何需要列表的人都可以迭代列表,即使列表为空(这将是一个非常快速的 for-each 循环)。

返回 null

如果您所处的环境内存不足是一个大问题,您可以优化为返回 null 值。然而,这意味着使用该方法的每个人总是需要检查 null,并且不能解决可能的内存泄漏问题。

It is developer's preference really.

Returning an empty list

Normally I'd return an empty list so that the receiver of the method's return object doesn't need to check for null and avoid any possible NullReferenceException.

So anyone that expects a list can iterate through the list even though the list is empty (that will be a very quick for-each loop).

Returning null

If you are in an environment where running out of memory is a large issue you could optimize to return null value instead. However that means that everyone that uses the method in question always need to check for null and doesn't solve the problem of possible memory leaks.

云之铃。 2024-10-13 15:36:10

如果出现问题,那么您不应该返回任何内容,而应该抛出异常。

您需要就 NULL 和 {} 的含义达成一致的项目方法并坚持下去。无论您是否使用 NULL,如果您是每个人都需要知道检查。

我喜欢考虑 NULL - 没有尝试或看看是否有什么,可能有一些,但谁知道呢。

空集合 - 尝试填充,但就系统而言,没有任何项目,这是一个相当强烈的声明。

例如钱包.笔记集合。

  • NULL - 我还没有打开钱包,所以我不知道里面是否有任何笔记。
  • List={} - 我已经查过了,我绝对没有任何笔记,因为我把所有的钱都花在了啤酒上。

If something goes wrong then you shouldn't be returning anything, rather throwing an exception.

You need to agree a consistent approach for the project as to the meaning of NULL and {} and stick to it. Either you are going to use NULL or not, if you are everyone needs to know to check.

I like to think of NULL - not tried to or see if there is anything, there might be some but who knows.

Empty collection - tried to populate and as far as the system is concerned there are no items, which is quite a strong statement.

e.g. Wallet.Notes collection.

  • NULL - I haven't opened my wallet, so I don't know if I have any notes in it.
  • List={} - I've checked and I definitely don't have any notes cos I spent it all on beer.
与他有关 2024-10-13 15:36:10

这是 Josh Bloch 的一篇文章,对此进行了解释。它是在 Java 上下文中编写的,但它应该同样适用于 C#。
返回零长度数组,而不是 null

Here is an article by Josh Bloch explaining the same. It's written in Java's context but it should apply to C# equally well.
Return zero-length arrays, not nulls

深者入戏 2024-10-13 15:36:10

尽管我想说这主要取决于开发人员的偏好,但返回空集合可能是更好的方法。

假设您有一个包含集合成员的对象。

public class Customer {
    private IList<Order> _orders;

    public Customer() {
        _orders = new List<Order>();
    }

    public IList<Order> Orders {
        get {
            return _orders;
        } 
    }
}

人们通常更愿意将此成员作为只读属性,以便其客户的订单不会在没有任何明显原因的情况下丢失。因此,返回 null 不是一个选项。使用空集合可能比使用空引用更好。因此,在类构造函数中实例化集合是一​​种更好的方法。

最重要的是,例如,在使用 DataBinding 时,返回空集合引用时可能会出现奇怪的行为,因为它最适合使用空集合。

另一个例子,当迭代一个集合时,例如:

foreach (Order o in c.Orders) {
    // Do something here...
}

当集合为空时,这个 foreach 循环将不会被执行,而不必先检查它是否为空引用。它简化了代码并最大限度地降低了其复杂性。

这取决于您正在工作的场景。

Although I'd say it's mostly a matter of developer's preference, to return an empty collection might be a better approach.

Let's say you have an object which contains a collection member.

public class Customer {
    private IList<Order> _orders;

    public Customer() {
        _orders = new List<Order>();
    }

    public IList<Order> Orders {
        get {
            return _orders;
        } 
    }
}

One generally will prefer to have this member as a readonly property so that its customer's orders don't get lost without any apparent reason. So, returning null is not an option. You would likely work better with an empty collection than a null reference. As such, instantiating the collection within the class constructor is a better approach.

And most importantly, when using DataBinding, for instance, you might get strange behaviour when returning null collection reference, as it will best work with an empty collection instead.

Another example, when iterating through a collection such as:

foreach (Order o in c.Orders) {
    // Do something here...
}

This foreach loop will simply not get executed when the collection is empty, without you having to check whether it is a null reference first. It simplifies the code and minimizes its complexity.

This depends on the scenario you're wokring in.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文