jeudi 1 août 2019

How to make this complex if-else statement maintainable in Kotlin

I wrote a function to get information out of the database based on requestparams. The following if-else statement is a huge problem. If we keep adding more filters we need to keep adding statement for all the possible paths.

    fun getMessages(name: String, pageable: Pageable, locale: String?, subject: String?,
                              recipient: String?): Page<MessageDTO>? {

        val messagePageable= if (!locale.isNullOrEmpty() && !subject.isNullOrEmpty() && !recipient.isNullOrEmpty()) {
            messageRepository.findAll(where(hasMessageName(name).and(hasLocale(locale!!)
            .and(hasSubject(subject!!).and(hasRecipient(recipient!!))))), pageable)
        } else if (!locale.isNullOrEmpty()) {
            messageRepository.findAll(where(hasMessageName(name).and(hasLocale(locale!!))), pageable)
        } else if (!subject.isNullOrEmpty()) {
            messageRepository.findAll(where(hasMessageName(name).and(hasSubject(subject!!))), pageable)
        } else {
            messageRepository.findAll(where(hasMessageName(name)), pageable)
        }
        return messagePageable.map { messageMapper.toMessageDTO(it) }.takeIf { it.content.isNotEmpty() }
}

There should be a better way of writting this. I appreciate your help.

Aucun commentaire:

Enregistrer un commentaire