gpt4 book ai didi

oop - 返回 null 是不好的设计吗?

转载 作者:行者123 更新时间:2023-12-03 04:32:18 25 4
gpt4 key购买 nike

我听到一些声音说检查方法返回的空值是糟糕的设计。我想听听其中的一些原因。

伪代码:

variable x = object.method()
if (x is null) do something

最佳答案

不返回 null 的基本原理是您不必检查它,因此您的代码不需要根据返回值遵循不同的路径。您可能想查看Null Object Pattern其中提供了更多相关信息。

例如,如果我要在 Java 中定义一个返回 Collection 的方法,我通常更愿意返回一个空集合(即 Collections.emptyList()),而不是 null,因为这意味着我的客户端代码更干净;例如

Collection<? extends Item> c = getItems(); // Will never return null.

for (Item item : c) { // Will not enter the loop if c is empty.
// Process item.
}

...比以下内容更干净:

Collection<? extends Item> c = getItems(); // Could potentially return null.

// Two possible code paths now so harder to test.
if (c != null) {
for (Item item : c) {
// Process item.
}
}

关于oop - 返回 null 是不好的设计吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1274792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com