如何实现List,Set和Map在零免费设计? [英] How to implement List, Set, and Map in null free design?
问题描述
它的伟大时,你可以返回在大多数情况下,空/空对象,以避免空值,但对于喜欢收藏的对象?
Its great when you can return a null/empty object in most cases to avoid nulls, but what about Collection like objects?
在Java中,地图
收益空
如果键
在 GET(键)
在地图上是找不到的。
In Java, Map
returns null
if key
in get(key)
is not found in the map.
我能想到的最好的方式,以避免空
S IN这种情况是返回一个进入< 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
.
当然,我们避免了空
,但现在你可以有一个类转换异常,如果你不检查其在 EmptyEntry&LT; T&GT;
。
Sure we avoid the null
, but now you can have a class cast exception if you don't check if its an EmptyEntry<T>
.
有没有更好的办法来避免空
S IN 地图的
GET( K)
?
Is there a better way to avoid null
s in Map
's get(K)
?
和为了论证的缘故,让我们说这种语言甚至没有空
,所以不要说只是使用零点
。
And for argument sake, let's say this language don't even have null
, so don't say just use nulls
.
推荐答案
有两种可能的解决方案:
Two possible solutions:
-
提供一个包含(Key)的功能。如果GET(键)称作一个不存在的键抛出异常。其缺点是:调用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.
函数式语言在类似情况下可能使用。本文介绍如何用Java 一可能实施>。
Functional languages use Maybe in similar situations. This article explains how to implement Maybe in Java.
这篇关于如何实现List,Set和Map在零免费设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!