Something came up in a code review at work recentl...
# codingconventions
t
Something came up in a code review at work recently, and I said I would ask what the consensus (if any) was in here. Suppose we're writing a REST application (Boot in this case, but that's not super important). Because we are trying to separate our layers, we have entity types (from a database) and DTOs that those get turned into when responding to clients. In some cases multiple entities can make up a single DTO. Nothing crazy so far. Further suppose for some resources, we have multiple views. For example we have a full view of an
Account
and perhaps a condensed version of the
Account
that contains a small fraction of the data in the full version. Does it seem reasonable to have something like this (made up example)?
Copy code
kotlin
data class AccountDto(login: String, firstName: String, lastName: String, city: String?, state: String?, zipCode: String?)
And then to convert it:
Copy code
kotlin
fun AccountEntity.toDto(full: Boolean = true): AccountDto =
  AccountDto(
    login = this.login,
    firstName = this.firstName,
    lastName = this.lastName,
    city = this.city.takeIf { full },
    state= this.state.takeIf { full },
    zipCode= this.zipCode.takeIf { full }
  )
Or would it be more reasonable to have two versions of
AccountDto
(one for full view and one for limited)? The issue brought up was that
takeIf { full }
did not look like something we had seen before. Once you read it it's clear, but the people reviewing wondered what others thought of this, and I said I would ask in here. 🙂 The fact that this is an extension function is not part of the problem, I just wrote it that way in here to be more compact.