神技巧:去掉烦人的 “ ! = null " (判空语句)
时间:2020-05-14 14:13:19
[导读]问题 为了避免空指针调用,我们经常会看到这样的语句 ...if (someobject != null) { someobject.doCalc();}... 最终,项目中会存在大量判空代码,多么丑陋繁冗!如何避免这种情况?我们是否滥用了判空呢? 精华回答: 这是初、中级程序猿经常会遇到的
问题
...if (someobject != null) {
someobject.doCalc();}...
最终,项目中会存在大量判空代码,多么丑陋繁冗!如何避免这种情况?我们是否滥用了判空呢?
public interface Action {
void doSomething();}
public interface Parser {
Action findAction(String userInput);}
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();}
2、精简
ParserFactory.getParser().findAction(someInput).doSomething();
因为无论什么情况,都不会返回空对象,因此通过findAction拿到action后,可以放心地调用action的方法。
其他回答精选:
1、如果要用equal方法,请用object<不可能为空>.equal(object<可能为空>))
例如使用 :
"bar".equals(foo)
而不是
foo.equals("bar")
免责声明:本文内容由21ic获得授权后发布,版权归原作者所有,本平台仅提供信息存储服务。文章仅代表作者个人观点,不代表本平台立场,如有问题,请联系我们,谢谢!






