如何在null自由设计中实现List,Set和Map? [英] How to implement List, Set, and Map in null free design?
问题描述
在大多数情况下可以返回一个null / empty对象以避免null,但是对象Collection的对象呢?
Its great when you can return a null/empty object in most cases to avoid nulls, but what about Collection like objects?
c> Map 返回 null
如果键
在 get )
在地图中找不到。
In Java, Map
returns null
if key
in get(key)
is not found in the map.
我可以想到避免 null $ c在这种情况下,$ c> s将返回
Entry< T>
对象,它是 EmptyEntry< T>
,或包含值 T
。
The best way I can think of to avoid null
s in this situation is to return an Entry<T>
object, which is either the EmptyEntry<T>
, or contains the value T
.
当然我们避免 null
,但现在你可以有一个类转换异常如果你不检查它的 EmptyEntry< T>
。
Sure we avoid the null
, but now you can have a class cast exception if you don't check if its an EmptyEntry<T>
.
是否有更好的方法来避免 Map
的
? null
> get(K)
Is there a better way to avoid null
s in Map
's get(K)
?
为了论证起见,让我们说这个语言甚至没有 null
,所以不要说只使用 nulls
。
And for argument sake, let's say this language don't even have null
, so don't say just use nulls
.
推荐答案
两种可能的解决方案:
-
提供contains(key)函数。如果为不存在的键调用get(key),则抛出异常。缺点是:在contains()之后调用get()重复操作;
Provide a contains(key) function. Throw an exception if get(key) is called for a non-existent key. The downside is: calling get() after contains() duplicates operations; not efficient.
功能语言在类似情况下使用Maybe。本文介绍了如何在Java中实现Maybe 。 / p>
Functional languages use Maybe in similar situations. This article explains how to implement Maybe in Java.
这篇关于如何在null自由设计中实现List,Set和Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!