Mar Mosh
Mar Mosh

Reputation: 275

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.

Upvotes: 0

Views: 537

Answers (1)

Jan B.
Jan B.

Reputation: 6448

Switch/Case won't make your statements more simple. Do some research on Boolean Algebra and how to simplify it, e.g. 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.

Upvotes: 1

Related Questions