Java 条件 - 如何使用 3 个场景格式化简单的 if 语句?if 结构建议

rob*_*anz 0 java formatting if-statement

我遇到一个问题,我的代码感觉很混乱,我需要一些帮助来更好地构建它。

例子:

if (object.getDescription() == Status.Expected && !logEvent.equals("Expected")) {
    System.out.println("Do nothing"); // ???
} else {
    status.setChangedBy(logEvent);
}
Run Code Online (Sandbox Code Playgroud)

如果以更干净的方式我该如何格式化它?我希望changedBy在每种情况下都调用该方法,除了 whengetDescription == Status.ExpectedlogEventis not "Expected"。但我也不想要一个空的 if 语句。

另一种选择是:

if (object.getDescription() == Status.Expected) {
   if (logEvent.equals("Expected")) {
         status.setChangedBy(logEvent);
   }
} else {
    status.setChangedBy(logEvent);
}
Run Code Online (Sandbox Code Playgroud)

这两个例子都有效。但这两个例子都“感觉不对”。还有其他我没有看到的解决方案吗?

Swe*_*per 6

!通过将运算符应用于整个事物来反转条件。然后就可以把代码放在ifblock中而不是elseblock中了。

if (!(object.getDescription() == Status.Expected && !logEvent.equals("Expected"))) {
    status.setChangedBy(logEvent);
}
Run Code Online (Sandbox Code Playgroud)

您可以使用德摩根定律进一步简化:

if (object.getDescription() != Status.Expected || logEvent.equals("Expected")) {
    status.setChangedBy(logEvent);
}
Run Code Online (Sandbox Code Playgroud)

当“描述不是预期的 logEvent预期的”时,您更改状态