gpt4 book ai didi

design-patterns - KeyNotFoundException 与在 Kotlin 中返回 null

转载 作者:行者123 更新时间:2023-12-02 13:05:33 24 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它.

2年前关闭。




Improve this question




我正在尝试决定 Kotlin 接口(interface)中的一个函数,该函数根据给定键从配置中读取值。这两个选项是

/**
* 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();
}

如果您选择第一个选项,这两种用法都会很尴尬/不可能。

关于design-patterns - KeyNotFoundException 与在 Kotlin 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com