我们团队的Java编码指南说:
避免使用"!" 在if语句中尽可能多.
我问其他同事,但没有人给我清楚的想法,因为该指南是很久以前创建的,作者可能已离开我们公司.
你有什么主意吗?
Bri*_*ick 11
根据提供的信息,这需要一些推测.一个可能的原因是,意图本身不是if语句,而是if-else语句.在这种情况下,我可以看到你可能会说你应该反转案件,以便你没有额外的否定操作.代替
if (! boolVar) {
// Something
} else {
// Something else
}
Run Code Online (Sandbox Code Playgroud)
你可能更喜欢
if (boolVar) {
// Something else
} else {
// Something
}
Run Code Online (Sandbox Code Playgroud)
这是否值得,可能更多的是品味和标准化问题.
该规则可能是罗伯特·马丁(Robert Martin)的《清洁法规》(Clean Code)第302页的改编版:
负面因素比正面因素难理解。因此,在可能的情况下,条件应该表示为肯定的。例如:
Run Code Online (Sandbox Code Playgroud)if(buffer.shouldCompact())优于
Run Code Online (Sandbox Code Playgroud)if(!buffer.shouldNotCompact())
举例来说,假设您正在创建一个验证器,该验证器要求两个要使该实体有效的条件为假:
自然的想法是为此编写两种方法:
boolean isCreatedWithinLastTwelveHours(BankAccount account)
boolean hasMoreThanTotalSumCap(BankAccount account)
Run Code Online (Sandbox Code Playgroud)
...此时,您将这些调用为:
boolean newAccount = isCreatedWithinTheLastTwelveHours(account);
boolean highEndAccount = hasMoreThanTotalSumCap(account);
if(!newAccount && !highEndAccount) { // ... other logic
// The more astute would use DeMorgan's law in an effort to make this more readable
if(!(newAccount || highEndAccount)) { // other logic
Run Code Online (Sandbox Code Playgroud)
嗯......那岂不是更好,如果你只是说,他们什么都没有呢?
boolean isNotCreatedWithinLastTwelveHours(BankAccount account)
boolean hasLessThanTotalSumCap(BankAccount account)
Run Code Online (Sandbox Code Playgroud)
这会使表达式更加简洁:
if(notNewAccount && notHighEndAccount) { // .. carry on!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3230 次 |
| 最近记录: |