Hey guys, Can we optimise or idiotmatic way this c...
# codereview
k
Hey guys, Can we optimise or idiotmatic way this code ?
Copy code
internal fun combineFullName(customerAddress: CustomerAddress?): CustomerAddress? {
    val fullName = if (customerAddress?.fullName.isNullOrEmpty()) {
        customerAddress?.firstName + " " + customerAddress?.lastName
    } else {
        customerAddress?.fullName
    }
    return customerAddress?.copy(fullName = fullName)
}
Thanks
j
What is
fullName
in the
CustomerAddress
definition? Can it have a value that is not first+last? Or does it always start empty/null and is then set by this function?
k
fullName
is a type of String. It has 2 condition. 1st Scenario
fullName
will be null then we need to set first+last. 2nd Scenario
fullName
will not be null then we don't need to set first+last because it has same value in first and last. Thanks
e
r
well, first point would be not passing nullable
CustomerAddress
to the function, as it serves no purpose here. Instead you would be better of using it as a receiver and turn any callsite of
combineFullName(someExpression)
to
someExpression?.combineFullName()
getting exact same results After that it looks pretty good, with small change:
Copy code
internal fun CustomerAddress.combineFullName(): CustomerAddress {
    val fullName = if (fullName.isNullOrEmpty()) { 
        "$firstName $lastName"
    } else {
        fullName
    }
    return copy(fullName = fullName)
}
And yes, it's a bad idea 😛
e
and it would probably make more sense as part of the construction of the class itself
r
Hmm true
j
Yeah it could just be a default value of
fullName
k
@ephemient actually I just write in short form first + last but in actual is
firstName + lastname
in my data class. Thanks for sharing that article. I'll remember in future
How can I do in the construction of class?
r
Copy code
data class Address(
    val first: String,
    val last: String,
    val full: String = "$first $last"
)

println(Address(first = "first", last = "last"))
println(Address(first = "first", last = "last", full = "weird full name"))
Prints
Copy code
Address(first=first, last=last, full=first last)
Address(first=first, last=last, full=weird full name)
k
Actually firstName, lastName and fullName is coming from server and it can null/empty that's why I used nullable
r
I chewed you out for using nullable argument for single argument function that does nothing and just returns
null
if it gets
null
- this is the purpose of
?.
operator, you don't really need to handle it in function Not for individual fields 😛 (and your above code currently does not really handle nullability... for example it would set fullName to
"null null"
if it got every field null, but you constructed a class from that)
k
In fact, I recently received a letter through the post, addressed as "Dear null". So this happens in production code too.
k
I got it thanks a million