我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
我使用x!=null以避免NullPointerException。还有其他选择吗?
if (x != null) {
// ...
}
当前回答
切勿将变量初始化为空。如果(1)不可能,则将所有集合和数组初始化为空集合/数组。
在您自己的代码中执行此操作,您可以避免!=空检查。
大多数时候,空检查似乎保护了集合或数组上的循环,所以只要将它们初始化为空,就不需要任何空检查。
// Bad
ArrayList<String> lemmings;
String[] names;
void checkLemmings() {
if (lemmings != null) for(lemming: lemmings) {
// do something
}
}
// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};
void checkLemmings() {
for(lemming: lemmings) {
// do something
}
}
这是一个很小的开销,但它值得更干净的代码和更少的NullPointerExceptions。
其他回答
最终,彻底解决这个问题的唯一方法是使用不同的编程语言:
在Objective-C中,你可以在nil上调用一个方法,而绝对不会发生任何事情。这使大多数空检查变得不必要,但会使错误更难诊断。在Nice这一Java派生语言中,所有类型都有两个版本:可能为空的版本和非空的版本。只能对非空类型调用方法。通过显式检查null,可以将可能为null的类型转换为非null类型。这使得更容易知道哪些地方需要空检查,哪些地方不需要空检查。
有一种很好的方法来检查JDK中的空值。Optional.java有大量解决这些问题的方法。例如:
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
帮助标枪真的非常非常有用。
我发现在这种情况下,Guava前提条件非常有用。我不喜欢将空值留给空指针异常,因为理解NPE的唯一方法是定位行号。生产版本和开发版本中的行号可能不同。
使用Guava Preconditions,我可以检查空参数并在一行中定义有意义的异常消息。
例如
Preconditions.checkNotNull(paramVal, "Method foo received null paramVal");
在Java中避免空检查的最佳方法是正确处理和使用异常。在我的经验中,随着您向前端移动,空检查变得越来越常见和必要,因为它更接近于通过UI提供无效信息的用户(例如,没有值,为字段提交)。
有人可能会争辩说,你应该能够控制UI正在做什么,以免你忘记大多数UI是通过某种类型的第三方库完成的,例如,根据情况或库的不同,它可能会为空白文本框返回NULL或空字符串。
您可以这样组合这两者:
try
{
myvar = get_user_supplied_value();
if (myvar == null || myvar.length() == 0) { alert_the_user_somehow(); return; };
process_user_input(myvar);
} catch (Exception ex) {
handle_exception(ex);
}
人们采取的另一种方法是:
if (myvar && myvar.length() > 0) { };
你也可以抛出一个异常(这是我更喜欢的)
if (myvar == null || myvar.length() == 0) {
throw new Exception("You must supply a name!");
};
但这取决于你。
在我看来,这似乎是初级到中级开发人员在某个时候往往会面临的一个相当普遍的问题:他们要么不知道,要么不信任他们正在参与的合同,并防御性地过度检查空值。此外,在编写自己的代码时,他们倾向于依赖于返回null来指示某些内容,从而要求调用者检查null。
换言之,有两种情况会出现空检查:
在合同条款中,null为有效响应;和如果它不是有效的响应。
(2) 很容易。从Java1.7开始,您可以使用Objects.requireOnNull(foo)
该方法的“正确”用法如下。该方法返回传递给它的对象,如果对象为空,则抛出NullPointerException。这意味着返回的值总是非空的。该方法主要用于验证参数。
public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
它也可以像断言一样使用,因为如果对象为空,它会抛出异常。在这两种情况下,都可以添加一条消息,该消息将显示在异常中。下面将其用作断言并提供消息。
Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
当值为null但不应为null时,通常会引发特定异常(如NullPointerException),这有利于引发更一般的异常(如AssertionError)。这是Java库采用的方法;当参数不允许为null时,支持NullPointerException而不是IllegalArgumentException。
(1) 有点难。如果你无法控制正在调用的代码,那么你就被卡住了。如果null是有效的响应,则必须检查它。
然而,如果是由你控制的代码(通常是这样),那就另当别论了。避免使用null作为响应。对于返回集合的方法,很容易:总是返回空集合(或数组)而不是空值。
对于非集合,这可能会更困难。举个例子:如果您有这些接口:
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
其中Parser接收原始用户输入并找到要做的事情,如果您正在实现某个命令行接口。现在,如果没有适当的操作,您可能会使契约返回null。这导致了你所说的空值检查。
另一种解决方案是从不返回null,而是使用空对象模式:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
比较:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
to
ParserFactory.getParser().findAction(someInput).doSomething();
这是一个更好的设计,因为它导致了更简洁的代码。
也就是说,findAction()方法抛出带有有意义的错误消息的异常可能是完全合适的——尤其是在这种情况下,您依赖于用户输入。findAction方法抛出一个异常比调用方法用简单的NullPointerException(没有解释)爆炸要好得多。
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
或者,如果您认为try/catch机制太难看,而不是Do Nothing,那么您的默认操作应该向用户提供反馈。
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}