考虑这一行:
if (object.getAttribute("someAttr").equals("true")) { // ....
Run Code Online (Sandbox Code Playgroud)
显然这条线是一个潜在的错误,属性可能是null,我们将得到一个NullPointerException.所以我们需要将它重构为以下两种选择之一:
第一种选择:
if ("true".equals(object.getAttribute("someAttr"))) { // ....
Run Code Online (Sandbox Code Playgroud)
第二种选择:
String attr = object.getAttribute("someAttr");
if (attr != null) {
if (attr.equals("true")) { // ....
Run Code Online (Sandbox Code Playgroud)
第一个选项很难读,但更简洁,而第二个选项在意图上是明确的,但是很冗长.
在可读性方面,您更喜欢哪个选项?
我有一个部分填充的对象数组,当我遍历它们时,我试图检查所选对象是否null在我用它做其他东西之前.然而,甚至检查它是否null似乎是通过a NullPointerException.array.length将包括所有null元素.你如何检查null数组中的元素?例如,在下面的代码中将为我抛出一个NPE.
Object[][] someArray = new Object[5][];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i]!=null) { //do something
}
}
Run Code Online (Sandbox Code Playgroud)