在教程(用于实现 xml 解析器)中,我看到了以下代码:
if( "NODENAME".equals(xmlreader.getNodeName()) ) { // getNodeName() returns java.lang.String
...
}
有理由写这样的字符串比较吗?
这可能是某种最佳/不良做法或类似的代码,可以带来一些性能优势。我想知道我是否应该在商业项目中使用它。
最佳答案
这使您免于 NullPointerException。
即Yoda Condition 用于解决不安全的 null 行为。
In programming jargon, Yoda Conditions (also called Yoda Notation) is a programming style where the two parts of an expression are reversed in a conditional statement.
优点是
Swapping the two conditional values does not change the behavior of the program. A common mistake is to accidentally assign a value instead of writing a conditional statement.
关于java - "String".equals(otherString) 有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18611050/