```// `cache` is an interface that has method `new...
# codingconventions
m
Copy code
// `cache` is an interface that has method `newToken()` & `unrecoverableSession()`
Which one do you guys prefer, on the following snippet code? 1️⃣
Copy code
if (retryCount > RETRY_LIMIT) {
             cache.unrecoverableSession()
             return null
        }

        cache.newToken()?.let { newToken ->
             return rewriteRequest(newToken)
        }

        return null
or 2️⃣
Copy code
if (retryCount > RETRY_LIMIT) {
            cache.unrecoverableSession()
            return null
        }

        val newToken = cache.newToken()

        return if (newToken != null) {
            rewriteRequest(newToken)
        } else {
            cache.unrecoverableSession()
            null
        }
or 3️⃣
Copy code
val newToken = cache.newToken()

        return when {
            retryCount > RETRY_LIMIT -> {
               cache.unrecoverableSession()
               null
            }
            newToken != null -> rewriteRequest(newToken)
            else -> {
               cache.unrecoverableSession()
               null
            }            
        }
3️⃣ 3
0️⃣ 1
l
Here is a more functional style which does the same if I'm not mistaken. One upside here is that whenever you are to return null,
cache.unrecoverableSession()
is run, unlike 1️⃣ in which you forgot one call
Copy code
return cache
    .takeUnless { retryCount > RETRY_LIMIT }
    ?.newToken()
    ?.let(::rewriteRequest)
    .also { if (it == null) cache.unrecoverableSession() }
🤯 1
t
@Luke definitely possible, but somehow I don't like using
takeIf/Unless
when I'm not checking anything o the receiver. For me that's more of a validation/filter function than something for controlling code flow. A simple it-condition is much easier to read and understand than this chain.
@miqbaldc I suggest flipping the first if-clause and doing something like this:
Copy code
if (retryCount <= RETRY_LIMIT) {
    cache.newToken()?.let {
        return rewriteRequest(it)
    }
}

cache.unrecoverableSession()
return null
👍 2
🙏 1