Context: There’s a migration process from `UserV1`...
# codingconventions
m
Context: There’s a migration process from
UserV1
to
UserV2
from our shared prefs Which one do you prefer? 1️⃣
UserV1
&
UserV2
is nullable if fetched from server, but we provide a blank/default value
Copy code
data class UserV1(status: String? = "", phoneNumber: String? = "", areaCode: Int? = -1)
data class UserV2(
   accountInfo: Account? = null,
   domicileInfo: Domicile? = null, 
)
data class Account(status: String? = "", phoneNumber: String? = "")
data class Domicile(areaCode: Int? = -1)

fun UserV1?.toUserV2() = UserV2(
    accountInfo = Account(status = this?.status.orEmpty(), phoneNumber = this?.phoneNumber.orEmpty()),
    domicileInfo = Domicile(areaCode = this?.areaCode ?: -1)
)
fun UserV2?.orEmpty() = UserV2()
Copy code
// wrapping the whole if condition, e.g: (if a else b).orEmpty()
fun findUser() = (if (userV2?.status?.isNullOrBlank() == false) userV2 else userV1.toUserV2()).orEmpty()
2️⃣
UserV1
&
UserV2
is nullable if fetched from server, and leave it null (no blank/default value)
Copy code
data class UserV1(status: String? = null, phoneNumber: String? = null, areaCode: Int? = null)
data class UserV2(
   accountInfo: Account? = null,
   domicileInfo: Domicile? = null, 
)
data class Account(status: String? = null, phoneNumber: String? = null)
data class Domicile(areaCode: Int? = null)

fun UserV1?.toUserV2() = UserV2(
    accountInfo = Account(status = this?.status.orEmpty(), phoneNumber = this?.phoneNumber.orEmpty()),
    domicileInfo = Domicile(areaCode = this?.areaCode ?: -1)
)
fun UserV2?.orEmpty() = UserV2()
Copy code
// call the `.orEmpty()` twice, e.g: if a.orEmpty() else b.orEmpty()
fun findUser() = if (userV2?.status?.isNullOrBlank() == false) userV2.orEmpty() else userV1.toUserV2().orEmpty()
2️⃣ 1
t
if your fields are nullable, why would you fill them with placeholder values? It will just be even more of a mess if you need to handle these "empty" fields somehow. Of course you should not only adapt the default values in the constructor declaration, but also remove all the fallback values (
.orEmpty()
/
?: -1
) in the mapping function. Also, I'd suggest making
accountInfo
and
domicileInfo
non-null properties and using an empty object as the default if necessary. That might also save you some null handling later.
🙏 1