I am creating the repository layer using Ktorm, so far I only have insert and update functions.
override fun create(
entity: ObjectEntity
): Either<DatabaseError, Entity> = try {
val id = database.insertAndGenerateKey(TableName) {
set(TableName.createdTimestamp, entity.createdTimestamp)
set(TableName.updatedTimestamp, entity.updatedTimestamp)
set(TableName.status, entity.status.id)
....
} as Int
entity.id = id
Either.Right(entity)
} catch (e: Exception) {
logger.error(e) {
...
}
Either.Left(DatabaseError(e.message))
}
override fun update(
entity: ObjectEntity
): Either<DatabaseError, Entity> = try {
val effectedRowCount = database.update(TableName) {
set(TableName.updatedTimestamp, entity.updatedTimestamp)
set(TableName.status, entity.status.id)
...
where { it.csmUUID eq entity.csmUUID }
}
if (effectedRowCount < 0) {
Either.Left(MissingEntityError(Entity::class.java, "csmUUID"))
} else {
Either.Right(entity)
}
} catch (e: Exception) {
logger.error(e) {
....
}
Either.Left(DatabaseError(e.message))
}
This code block works like a charm with no issues. But the thing is, there are a lot of fields (more than 20) that are being set in both functions. This causes a code duplication and because of this I can't pass the code quality gate and merge it. Also, I don't like having this much duplicate code. Any suggestions to prevent code duplication in a scenario like this?