返回 null 是糟糕的设计吗? [英] Is returning null bad design?

查看:29
本文介绍了返回 null 是糟糕的设计吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've heard some voices saying that checking for a returned null value from methods is bad design. I would like to hear some reasons for this.

伪代码:

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

推荐答案

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

The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.

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

For example, if I were to define a method in Java that returned a Collection I would typically prefer to return an empty collection (i.e. Collections.emptyList()) rather than null as it means my client code is cleaner; e.g.

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.
  }
}

这篇关于返回 null 是糟糕的设计吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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