如何在 Kotlin 中维护这个复杂的 if-else 语句

我写了一个函数来根据请求参数从数据库中获取信息。下面的 if-else 语句是一个大问题。如果我们继续添加更多过滤器,我们需要继续为所有可能的路径添加语句。


    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() }

}

应该有更好的写法。我感谢您的帮助。


侃侃尔雅
浏览 116回答 2
2回答

慕田峪9158850

我不确定,但也许一些重构会有所帮助。例如,您似乎正在对request数据库使用某种形式,如果根据参数进行填充,那么也许可以像这样进行管理。fun getMessages(name: String, pageable: Pageable, locale: String?, subject: String?,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; recipient: String?): Page<MessageDTO>? {&nbsp; &nbsp; val request = where(hasMessageName(name))&nbsp; &nbsp; locale?.let{ request.and(hasLocale(it)) }&nbsp; &nbsp; subject?.let{ request.and(hasSubject(it)) }&nbsp; &nbsp; recipient?.let{ request.and(hasRecipient(it))}&nbsp; &nbsp; return messageRepository.findAll(request, pageable)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map { messageMapper.toMessageDTO(it) }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .takeIf { it.content.isNotEmpty() }}在这里,我不确定.and()方法是如何工作的,所以也许它应该是这样的: request = request.and(...)

慕容森

您可以if用一个when语句替换您的语句,以便更容易阅读:fun getMessages(name: String, pageable: Pageable, locale: String?, subject: String?,                              recipient: String?): Page<MessageDTO>? = when {    !locale.isNullOrEmpty() && !subject.isNullOrEmpty() && !recipient.isNullOrEmpty() ->        messageRepository.findAll(where(hasMessageName(name).and(hasLocale(locale!!)            .and(hasSubject(subject!!).and(hasRecipient(recipient!!))))), pageable)    !locale.isNullOrEmpty() ->        messageRepository.findAll(where(hasMessageName(name).and(hasLocale(locale!!))), pageable)    !subject.isNullOrEmpty() ->        messageRepository.findAll(where(hasMessageName(name).and(hasSubject(subject!!))), pageable)    else ->        messageRepository.findAll(where(hasMessageName(name)), pageable)}.map { messageMapper.toMessageDTO(it) }.takeIf { it.content.isNotEmpty() }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java