2017-12-02 113 views
1

你會怎樣用更多kotlinic的方式編寫下面的代碼?什麼時候應該使用let {},什麼時候只是簡單的!= null

var returnValue = ... 
val s3data = presignedUrl.body() 
if (s3data != null) { 
    val uploadImage = api.uploadImage(s3data.bucketUrl, s3data.awsAccessKeyId, s3data.policy, s3data.key, s3data.signature, body).execute() 
    if (!uploadImage.isSuccessful) { 
     crashReporterService.sendIssue("Failed uploading file", "Failed uploading file ${uploadImage.raw()}") 
     returnValue = Result.FAILURE 
    } else { 
     returnValue = Result.SUCCESS 
    } 
} else { 
    crashReporterService.sendIssue("Failed uploading image", "Error - ${presignedUrl.raw()}") 
    returnValue = Result.FAILURE 
} 

return returnValue 

我可以用讓,但我覺得它使代碼更復雜,難以理解

+0

關於你的代碼的一個註釋:返回asap是一個很好的練習afaik,縮小範圍並簡化邏輯 – DPM

回答

4
  • 常見共享代碼 - 在這種情況下,錯誤報告和失敗結果返回 - 可合併爲local function
  • 導致返回的可空性(在這種情況下,s3data可爲空)通常可以用返回的?: elvis operator代替。
  • 當反覆輸入相同的變量(在這種情況下,訪問s3data)時,run塊是適當的。如果混淆,請參閱What is a "receiver" in Kotlin?
  • 正如另一個答案中所述,如果/ else塊是Kotlin中的表達式。

因此我會發現下面的實現最ideomatic,受本地函數的參數恰當的命名:

fun foo() { 
    fun failure(p0: String, p1: String) = crashReporterService.sendIssue(p0, p1).let { Result.FAILURE } 
    val s3data = presignedUrl.body() ?: return failure("Failed uploading image", "Error - ${presignedUrl.raw()}") 
    val uploadImage = s3data.run { api.uploadImage(bucketUrl, awsAccessKeyId, policy, key, signature, body).execute() } 

    return if (uploadImage.isSuccessful) { 
     Result.SUCCESS 
    } else { 
     failure("Failed uploading file", "Failed uploading file ${uploadImage.raw()}") 
    } 
} 

你的問題是在代碼審查接壤,所以你可能也很高興知道有一個dedicated Stack Exchange network just for that.然而,之前讀A guide to Code Review for Stack Overflow users

4

if/else is an expression in Kotlin,所以下面肯定更是Kotlinesque:

val s3data = presignedUrl.body() 
return if (s3data != null) { 
    val uploadImage = api.uploadImage(s3data.bucketUrl, s3data.awsAccessKeyId, s3data.policy, s3data.key, s3data.signature, body).execute() 
    if (!uploadImage.isSuccessful) { 
     crashReporterService.sendIssue("Failed uploading file", "Failed uploading file ${uploadImage.raw()}") 
     Result.FAILURE 
    } else { 
     Result.SUCCESS 
    } 
} else { 
    crashReporterService.sendIssue("Failed uploading image", "Error - ${presignedUrl.raw()}") 
    Result.FAILURE 
} 
相關問題