繁体   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