Stackoverflow 高赞答案,为什么牛逼的程序员都不用 “ ! = null
时间:2021-10-26 14:06:15
手机看文章
扫描二维码
随时随地手机看文章
[导读]来源:blog.csdn.net/lizeyang/article/details/40040817为了避免空指针调用,我们经常会看到这样的语句。...if (someobject != null) { someobject.doCalc();}...最终,项目中会存在大量...
为了避免空指针调用,我们经常会看到这样的语句。
if (someobject != null) {
someobject.doCalc();
}
... 最终,项目中会存在大量判空代码,多么丑陋繁冗!如何避免这种情况?我们是否滥用了判空呢?
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
} 其中,Parse 有一个接口 FindAction,这个接口会依据用户的输入,找到并执行对应的动作。假如用户输入不对,可能就找不到对应的动作(Action),因此 findAction 就会返回 null,接下来 action调用 doSomething 方法时,就会出现空指针。
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;
}
}} 对比下面两份调用实例。
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();
} 2、精简
因为无论什么情况,都不会返回空对象,因此通过 findAction 拿到 action 后,可以放心地调用 action 的方法。
if (someobject != null) {
someobject.doCalc();
}
... 最终,项目中会存在大量判空代码,多么丑陋繁冗!如何避免这种情况?我们是否滥用了判空呢?
- null 是一个有效有意义的返回值(Where null is a valid response in terms of the contract; and)
- null是无效有误的(Where it isn't a valid response.)
- assert 语句,你可以把错误原因放到 assert 的参数中,这样不仅能保护你的程序不往下走,而且还能把错误原因返回给调用方,岂不是一举两得。(原文介绍了 assert 的使用,这里省略)
- 也可以直接抛出空指针异常。上面说了,此时 null 是个不合理的参数,有问题就是有问题,就应该大大方方往外抛。
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
} 其中,Parse 有一个接口 FindAction,这个接口会依据用户的输入,找到并执行对应的动作。假如用户输入不对,可能就找不到对应的动作(Action),因此 findAction 就会返回 null,接下来 action调用 doSomething 方法时,就会出现空指针。
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;
}
}} 对比下面两份调用实例。
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();
} 2、精简
因为无论什么情况,都不会返回空对象,因此通过 findAction 拿到 action 后,可以放心地调用 action 的方法。





