为什么不鼓励不可变的 null?

Why immutable null is discouraged?

我目前正在使用不可变库从我的 Web 应用程序生成 JSON 对象。

this章,第一行说:

The use of nullable attributes is discouraged.

所以我的问题是:

1) 为什么?空对象有什么问题?

2) 如果我使用第三方对象的包装器并且我不知道 item 是否为 null,那么使用分类构建器代码将失败怎么办:

MyImmutableWrapperObject
    .builder().
    .mobile(input.getMobile()) // don't know if null or not
    .build();

有没有最优解?

编辑:

@JsonProperty("mobile")
public abstract Optional<String> mobile();  

...

// composing builder
if (input.getMobile() != null)
        builder.mobile(input.getMobile());

生成的json是:

"mobile": {
    "present": false
},

如何彻底删除空白字段?

我读过 this,但是它使用 gson.toJson 其中 return 一个 String 对象,这不是我想要的方式。

编辑后:

我刚刚发现 Optional 即使存在也不会显示实际值,但它只显示 true/false 值,所以我不需要它。

这正是 IMO 的重点,您不知道对象是否为 null;所以当以后使用它时,你可能会明显得到一个 NullPointerException。通过使用禁止这样做的库,您将不会关心某些东西是否为 null(因为它不会为 null),因此代码和 if 语句更少,这些语句会通过潜在的 null 检查污染代码。

还有一个空引用在不同的上下文中可能意味着不同的事情。例如,我看到代码需要 Boolean 的三个状态:truefalse 和尚未设置(如 null)。我发现那是错误的,但仍然偶尔会看到它。

这就是为什么 Optional 在 Guava 中引入并且现在在 JDK 中引入的原因。它迫使用户主动使用 Optional 做某事。例如:

  Optional<Integer> i...

  if(i.isPresent()).... // you are forced to do this check

很明显你可以这样做:

 i.get()

但是该方法被记录在案,它可能会失败。

同样的,对于一个参考来说根本就不是这样:

 Integer i  = null;
 if(i == null) // this is not an operation that is mandatory

迄今为止我 seen/read 关于这个主题的博文是 Guava explanation