Return 令人困惑的布尔语句 - 重构
Return confusing boolean statement - refactoring
我写了一个方法:
private boolean checkIfCanBeSent(Product product, Type type, TypeToSend typeToSend) {
boolean isDisabled = isStatusDisabled(product, type);
boolean isManual = isManual(typeToSend);
return !(isDisabled && !isManual);
}
它工作正常,但是在同行评审期间收到评论说这个 return 声明令人困惑。如何改进它并使其更具可读性?
三点建议。
- 应用德摩根定律给出等价的陈述。
- "enabled"比"not disabled"更容易理解。
- 不要让变量与方法同名。
所以
boolean isEnabled = ! isStatusDisabled(product, type);
boolean isManualType = isManual(typeToSend);
return isEnabled || isManualType;
我写了一个方法:
private boolean checkIfCanBeSent(Product product, Type type, TypeToSend typeToSend) {
boolean isDisabled = isStatusDisabled(product, type);
boolean isManual = isManual(typeToSend);
return !(isDisabled && !isManual);
}
它工作正常,但是在同行评审期间收到评论说这个 return 声明令人困惑。如何改进它并使其更具可读性?
三点建议。
- 应用德摩根定律给出等价的陈述。
- "enabled"比"not disabled"更容易理解。
- 不要让变量与方法同名。
所以
boolean isEnabled = ! isStatusDisabled(product, type);
boolean isManualType = isManual(typeToSend);
return isEnabled || isManualType;