use*_*893 16 java boolean-expression
我在其中一个项目中遇到过这段代码
(这是Java)
if (Boolean.TRUE.equals(foo.isBar()))
Run Code Online (Sandbox Code Playgroud)
Foo#isBar()被定义为boolean isBar(),所以它无法返回null
真的有什么理由说它应该这样写吗?我自己也会写
if (foo.isBar())
Run Code Online (Sandbox Code Playgroud)
,但也许我错过了一些微妙的东西.
谢谢
Yog*_*ngh 19
我希望foo.isBar()返回一个布尔值.在这种情况下,你总是可以写if (foo.isBar()).如果你foo.isBar()返回Boolean那么它可以是Boolean.TRUE,Boolean.FALSE或NULL.在这种情况下if (Boolean.TRUE.equals(foo.isBar())),确保if块在一个场景中执行(TRUE)并在剩余2中省略.
返回布尔值NULL if (foo.isBar()) 时 ,将失败foo.isBar() .
Kev*_*vin 14
由于isBar返回原语boolean,因此没有语义差异.此外,第二种方式更简洁,更清晰,更有效,因为结果不必为调用自动装箱,然后再次提取原始布尔值.鉴于这一切,没有理由使用第一种方法,而有几种方法使用第二种方法,所以使用第二种方法.我给其他编码人员留下了很大的余地,但我会坐下来与任何向专业代码添加类似内容的人聊聊.
小智 5
我会怀疑“没有充分理由的旧遗留代码” - 事实上,我认为它更糟。(我想知道如何int比较 ..)
使用的代码TRUE.equals需要一个装箱转换,一个额外的方法调用(以及里面的所有东西),最后,它看起来很草率。
我知道的唯一原因是 iffoo.isBar 被输入为返回Boolean(not boolean) 以及它可能返回的位置null:
Boolean b = null;
// throws an exception when it tries to unbox b because it is null
boolean isTrue1 = (boolean)b;
// evaluates to false
boolean isTrue2 = Boolean.TRUE.equals(b);
// evaluates to false as well
boolean isTrue3 = b != null ? (boolean)b : false;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12431 次 |
| 最近记录: |