为什么牛逼的程序员都不用 “ ! = null " 做判空?
...if (someobject != null) { someobject.doCalc();}...终,项目中会存在大量判空代码,多么丑陋繁冗!如何避免这种情况?我们是否滥用了判空呢?
public interface Action { void doSomething();}
public interface Parser { Action findAction(String userInput);}其中,Parse有一个接口FindAction,这个接口会依据用户的输入,找到并执行对应的动作。假如用户输入不对,可能就找不到对应的动作(Action),因此findAction就会返回null,接下来action调用doSomething方法时,就会出现空指针。
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();# 其他回答精选:
1、如果要用equal方法,请用object<不可能为空>.equal(object<可能为空>))
例如使用 :
"bar".equals(foo)而不是
foo.equals("bar")作者:lizeyang
来源:blog.csdn.net/lizeyang/article/details/40040817
相关文章