簡體   English   中英

如果if語句具有多個條件,則長-如何替換?

[英]Long if else statement with multiple condition - 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);
}

我在Google上閱讀過,如果if語句是switch語句,則對多個語句是有好處的,但是我在這里有多個條件,所以我不知道如何解決這個問題:/我需要比長的if else語句更好的解決方案,因為它很丑陋。

Switch / Case不會使您的陳述更簡單。 對布爾代數及其簡化方法進行一些研究,例如,使用卡諾圖。

https://zh.wikipedia.org/wiki/卡諾地圖

由於您的代碼中有很多重復(狀態== null),您可能最終會得到一些嵌套的if statements ,這會使您的代碼至少更具可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM