jeudi 7 janvier 2021

Kotlin best approach

I have a function fetchDetails() which is supposed to inspect the id using the client, identify which type of device it is (A, B, C) and then perform a series of operations to construct the deviceDetails of appropriate type and then return it. What would be the good design approach for this task? I don't think a set of if-else (below) statements would be the right way to go. DeviceA, DeviceB, DeviceC will have more value than just addInfo, I included only so much to keep it simple here.

fun fetchDetails(id: deviceId): DeviceDetails? {
        //construct details depending on whether device is of type A, B, C and return deviceA, 
          deviceB or deviceC
        if(client.typeOf(id) == A)
           return constructDetailsA(id)
        if(client.typeOf(id) == B)
           return constructDetailsB(id)
        .....
    }
class DetailFetcher(private val client: clientWrapper) {

    fun fetchDetails(id: deviceId): DeviceDetails? {
        //construct details depending on whether device is of type A, B, C and return deviceA, 
          deviceB or deviceC
    }

}

sealed class DeviceDetails
data class DeviceA(val addInfo: String) : DeviceDetails()
data class DeviceB(val addInfo: String) : DeviceDetails()
data class DeviceC(val addInfo: String) : DeviceDetails()

Aucun commentaire:

Enregistrer un commentaire