Skip to content

Instantly share code, notes, and snippets.

@j-didi
Last active June 9, 2020 21:25
Show Gist options
  • Save j-didi/e2adf93095ad77947d6fd5bde9be67a9 to your computer and use it in GitHub Desktop.
Save j-didi/e2adf93095ad77947d6fd5bde9be67a9 to your computer and use it in GitHub Desktop.
Kotlin simple functions delegate implementation example
import java.time.LocalDate
//Domain entity, command an result from CQRS
data class Person(val id: Int, val name: String, val createdAt: LocalDate, val updateAt: LocalDate)
data class PersonCommand(val name: String)
data class PersonResult(val id: Int, val name: String)
//Repository, Logger and Mapper abstractions
interface Repository<T> { fun insert(entity: T) : T }
interface Logger { fun log(content: String) }
interface Mapper<TEntity, TCommand, TResult> {
fun fromEntityToResult(entity: TEntity) : TResult
fun fromCommandToEntity(command: TCommand) : TEntity
}
//AppService abstraction and implementation using delegate functions
interface PersonAppService { fun save(command: PersonCommand) : PersonResult }
class PersonAppServiceImpl (
repository: Repository<Person>,
logger: Logger,
mapper: Mapper<Person, PersonCommand, PersonResult>
) :
PersonAppService,
Repository<Person> by repository,
Logger by logger,
Mapper<Person, PersonCommand, PersonResult> by mapper
{
override fun save(command: PersonCommand) : PersonResult {
val entity = fromCommandToEntity(command) //Mapper
insert(entity) //Repository
log("${entity.id}: ${entity.name} created at ${LocalDate.now()}") //Logger
return fromEntityToResult(entity) //Mapper
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment