DEV Community

Abdalla Elnaggar
Abdalla Elnaggar

Posted on

2 2

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 : {},
y:10
}
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

xResposne.isSuccess()

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

open class BaseResponse {
    @SerializedName("Status")
    val status: String = "Failures"
    @SerializedName("Message")
    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(
    @SerializedName("news")
    val news: ArrayList<New>,
    @SerializedName("pageCount")
    val pageCount: Int,
):BaseResponse()
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 (it.name == "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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay