Jor*_*oba 1 null design-patterns kotlin
我正在尝试确定Kotlin界面中的某个功能,该功能会根据一个Give键从配置中读取一个值。这两个选择是
/**
* 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
Run Code Online (Sandbox Code Playgroud)
/**
* 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?
Run Code Online (Sandbox Code Playgroud)
如图所示,主要区别在于引发异常或返回空值。
考虑到我在Java和C#中的背景,我很自然地编写第二种形式,并要求调用者在访问该值之前检查null,但是我不确定这是否适用于Kotlin或是否有一般偏好以避免返回null值尽可能。
在Kotlin中,您具有不错的null处理。因此与java相对,无需避免null,可以接受它。
因此,我将选择您的第二个选项,并让您的Api消费者自行决定。
他们可以使用猫王操作员:
val value = readValue("key") ?: "";
val value2 = readValue("key2") ?: throw IllegalArgumentException();
Run Code Online (Sandbox Code Playgroud)
或添加他们要使用的确切扩展方法。
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();
}
Run Code Online (Sandbox Code Playgroud)
如果您选择第一种方法,那么两种用法都将很尴尬/不可能。
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |