https://kotlinlang.org logo
#codereview
Title
# codereview
i

ivano

01/21/2020, 2:21 PM
Copy code
companion object {
        fun <T> fromData(data: T): Result<T> {

            return Result(data, null)
        }

        fun <T> fromError(error: Throwable): Result<T> {

            return when (error) {
                is HttpException -> {
                    if (error.code() in 400..499) {

                        if (error.code() == 401) AccountStorage().signOut()

                        mapErrorBody(error, PAErrorModel::class.java)?.let {
                            return Result(null, it)
                        } ?: return Result(null, PAErrorModel("", error.localizedMessage))
                    }

                    return Result(null, PAErrorModel("", error.localizedMessage))
                }
                else -> Result(null, error)
            }
        }
    }
I solved as this!
Copy code
class Result<T>(val data: T? = null, val error: Throwable? = null) {

    companion object {
        fun <T> fromData(data: T): Result<T> {

            return Result(data, null)
        }

        fun <T> fromError(error: Throwable): Result<T> {

            return if (error is HttpException) {
                manageCodeHttpException(error)
            } else Result(null, error)
        }

        private fun <T> manageCodeHttpException(error: HttpException): Result<T> {

            return checkRange(error)
                

        }

        private fun <T> checkRange(error: HttpException): Result<T> {
            if (error.code() in 400..499) {
                if (error.code() == 401) AccountStorage().signOut()

                mapErrorBody(error, PAErrorModel::class.java)?.let {
                    return@let Result(null, it)
                } ?: return Result(null, PAErrorModel("", error.localizedMessage))
            }

            return Result(null, PAErrorModel("", error.localizedMessage))
        }
    }
m

Mike

01/21/2020, 3:06 PM
you could also remove all the
return
statements in the
is HttpException
, and add an
else
to the
if(error.code() in 400..499)
to wrap the
Result(null, PAErrorModel("", error.localizedMessage)
return value. This will keep it all in one function.
And I might do additional refactoring as all the branches inside the HttpException return a
Result
with the first element null anyway.
l

Luis Munoz

01/23/2020, 4:40 PM
in my opinion the number 1 problem with code I see is functions doing too much
easier to test, understand, and moves things around if everyone just made their functions smaller
m

Mike

01/23/2020, 6:04 PM
@Luis Munoz About the only thing I'd suggest is relying on the fact that things are expressions rather than the explicit
return
statements in your functions.
i

ivano

01/27/2020, 9:42 AM
thank you for the nice suggestions
3 Views