有没有办法缩短对同一个变量的连续逻辑运算?
示例:
if (animation.getStatus() == Animation.Status.PAUSED || animation.getStatus() == Animation.Status.STOPPED) {
animation.playFromStart();
} else if (animation.getStatus() == Animation.Status.RUNNING) {
animation.stop();
}
您在 if 子句中看到我检查了 animation.getStatus()
两次,一次用于暂停,一次用于停止。
有没有办法让它像 animation.getStatus() == Animation.Status.PAUSED ||动画.Status.STOPPED
?
我确定已经有人问过这个问题,但我真的不知道要搜索什么,所以如果这是重复的,我很抱歉。
最佳答案
没有; Java 语法是不可变的。
有几个选项,但最简单的是重构,作为奖励使其清晰易读,例如,
if (animation.shouldReplay()) {
animation.playFromStart();
} else if (animation.shouldStop() {
animation.stop();
}
或更深一层,例如,
animation.controlFromCurrentStatus();
如果您不愿意封装,只需导入状态即可:
Animation.Status currentStatus = animation.getStatus();
if (currentStatus == PAUSED || currentStatus == STOPPED) {
animation.playFromStart();
} else if (currentStatus == RUNNING) {
animation.stop();
}
或者使它们成为 enum
,无论如何它们都应该是:
switch (currentStatus) {
case PAUSED:
case STOPPED:
animation.playFromStart();
break;
case RUNNING:
animation.stop();
}
关于java - 如何在 Java 中编写简短的逻辑表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29042173/