DEV Community

Abdalla Elnaggar
Abdalla Elnaggar

Posted on

Digging down for isSuccess() in bad API response

Nothing frustrating than a bad design api, what if you have such api

status : "Success",
message : "",
x : {},
Enter fullscreen mode Exit fullscreen mode

as the sample above x can be changed from api to another and some time there is other key along side.
what I want to say every response has status and message but we don't know what it has alongside with it, that task here is to know that if the response came with success or failed,
you can deserialize each response to its object and then check

xResponse.success = "Success"

for each type, that bad and I dont want to do that each time,
I want


there is two solution:
first one is base class and make every response class extend it

open class BaseResponse {
    val status: String = "Failures"
    val message: String = ""
fun BaseResponse.isSuccessful(): Boolean {
    if (status == "Success") {
        return true
    return false
Enter fullscreen mode Exit fullscreen mode

and then

data class ArticlesResponse(
    val news: ArrayList<New>,
    val pageCount: Int,
Enter fullscreen mode Exit fullscreen mode

I don't like this solution because every new response class has to extend this base response, this extra for every response.
solution number two is reflection, because we know that every response class has a status property we can use that knowledge to create method that do reflection.
don't forget to add the reflection library
implementation "org.jetbrains.kotlin:kotlin-reflect:1.6.21"
then the actual work

fun Any.isSuccess(): Boolean {
    val clazz = this.javaClass.kotlin
    clazz.memberProperties.forEach {
        if ( == "status") {
            val status = it.get(this)
            return status == "Success"
    return false
Enter fullscreen mode Exit fullscreen mode

and that is it, the problem with this solution is you get isSuccess() extension method on every class

Top comments (0)