Which one is better (readable, performant, etc)? A...
# codereview
s
Which one is better (readable, performant, etc)? A:
Copy code
suspend fun getValue(): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    if(condition) {
 return@withContext CONST
    } else {
        if(disk.readValueFromDisk() == "") {
            val newValue = Generator.generateValue().toString()
            disk.writeValueToDisk(newValue)
        }
    return@withContext disk.readValueFromDisk()    
    }
}
B:
Copy code
suspend fun getValue(): String = if(condition) CONST else withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    disk
    .readValueFromDisk()
    .takeIf { it.isNotEmpty() }
    ?: Generator
       .generateValue()
       .toString()
       .also {
            disk.writeValueToDisk(it)
        }
}
j
There are many things here. I would avoid calling
withContext
unnecessarily, so if you have a condition where it's not useful to switch threads, don't. A second thing is about storing the value you read from disk. In B, you use functional operators and read only once. In A, you don't use functional operators, but that doesn't mean you can't store the result you read in a variable