简体   繁体   中英

Long if else statement with multiple condition - how to replace it?

I have a problem with very long if else, but I really don't have idea how to replace it.

List<Comment> commentList;
if (EnumUtils.isValidEnum(Comment.State.class, state) && ordered && petUuid == null) {
    commentList = commentRepository.findByStateOrderByCreatedDesc(Comment.State.valueOf(state));
} else if (EnumUtils.isValidEnum(Comment.State.class, state) && !ordered && petUuid == null) {
    commentList = commentRepository.findByState(Comment.State.valueOf(state));
} else if (state == null && ordered && petUuid == null) {
    commentList = commentRepository.findAllByOrderByCreatedDesc();
} else if (state == null && !ordered && petUuid == null) {
    commentList = commentRepository.findAll();
} else if (EnumUtils.isValidEnum(Comment.State.class, state) && !ordered && petUuid != null) {
    commentList = commentRepository.findByPetUuidAndByState(petUuid, Comment.State.valueOf(state));
} else if (EnumUtils.isValidEnum(Comment.State.class, state) && ordered && petUuid != null) {
    commentList = commentRepository.findByPetUuidAndByStateOrderByCreatedDesc(petUuid, Comment.State.valueOf(state));
} else if (state == null && !ordered && petUuid != null) {
    commentList = commentRepository.findByPetUuid(petUuid);
} else if (state == null && ordered && petUuid != null) {
    commentList = commentRepository.findByPetUuidOrderByCreatedDesc(petUuid);
} else {
    throw new WrongEnumValueException(Comment.State.class);
}

I read in Google that good for multiple if is switch statement but I have multiple conditions here so I don't know how to solve this problem :/ I need some better solution than this long if else statement because it's just ugly.

Switch/Case won't make your statements more simple. Do some research on Boolean Algebra and how to simplify it, eg with Karnaugh Maps.

https://en.wikipedia.org/wiki/Karnaugh_map

As you have a lot of repetitions in your code (state == null) you probably will end up with some nested if statements that will make your code at least a little more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM