design-patterns - KeyNotFoundException 与在 Kotlin 中返回 null
问题描述
我正在尝试决定 Kotlin 接口中的一个函数,该函数根据给定键从配置中读取值。这两个选项是
/**
* Reads a configuration value for the specified key.
* @param key The key to the configuration value to retrieve
* @return The configuration value if the key is present, exception otherwise
*/
fun readValue(key: String): String
/**
* Reads a configuration value for the specified key.
* @param key The key to the configuration value to retrieve
* @return The configuration value if the key is present, null otherwise
*/
fun readValue(key: String): String?
如图所示,主要区别在于引发异常或返回空值。
鉴于我在 Java 和 C# 方面的背景,我觉得编写第二种形式并要求调用者在访问值之前检查 null 是很自然的,但是我不确定这是否适用于 Kotlin,或者一般偏好避免返回 null尽可能的值。
解决方案
在 Kotlin 中,您可以进行不错的 null 处理。所以反对java,不用避免null,可以拥抱它。
所以我会选择你的第二个选项,让你的 Api 的消费者自己决定。
他们可以使用 Elvis Operator:
val value = readValue("key") ?: "";
val value2 = readValue("key2") ?: throw IllegalArgumentException();
或者添加他们想要使用的确切扩展方法。
fun Repository.readOrEmpty(key:String):String {
return this.readValue(key)?:""
}
fun Repository.readOrElse(key:String, defaultValue:String):String {
return this.readValue(key)?:defaultValue
}
fun Repository.readOrThrow(key:String):String {
return this.readValue(key)?:throw IllegalArgumentException();
}
如果您选择第一个选项,这两种用法都会很尴尬/不可能。
推荐阅读
- xcode - AudoiDeviceGetCurrentTime:xcode 中没有给定 ID 错误的设备
- apache-kafka - 如何在生产者端使用 Kafka 进行容错
- oracle - 将 Netbeans 连接到 Oracle SQL(远程主机)引发异常
- angular - @NgRx 如何在实体之间建立多对多关系?
- json - 正则表达式范围选择
- c# - 需要不强制数据一致性的高性能 C# 集合
- reactjs - MDB DataTable text-align on th 和 td 在 ReactJS
- java - 是否有任何 API 可用于阿联酋通行证的数字签名
- gstreamer - “多路复用器”有什么用。在管道命令中
- sql - 如何使用新属性值更新 JSON 列?