这个问题对于我来说是一个很常见的问题,这也是由初级程序员成长到中级程序员的时候经常会遇到的问题。程序员不知道或不信任正在使用的约定,并且小心的检查着null。还有当程序员写代码的时候,总是会依赖于通过返回空(NULL)来表明某些意义,因此需要调用者去检查Null。换种方式来说,有两种空指针的检查场景:
- 期望的结果就是null。
- 期望的结果不是null。
第二种很简单,可以通过用assert或者允许程序报错,例如抛出NullPointerException。Assertions是一个从Java1.4加进来的高度未被利用的特性,语法是:
assert <condition>
或者
assert <condition> : <object>
condition是一个布尔表达式,object是一个对象(其toString()方法的输出将会被包含在错误里)。
校对注:我测试了下,JDK1.4及其以上,运行前设置vm参数-ea
public static void main(String[] args) { String name = null; assert (name != null) : "name为空null"; }
Exception in thread "main"; java.lang.AssertionError: 变量name为空null at LogUtil.main(LogUtil.java:37)
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(); }
和这段:
ParserFactory.getParser().findAction(someInput).doSomething();
这是个更好的设计,因为足够简洁,避免了多余的判断。即便如此,或许比较合适的设计是:findAction()方法之恶杰抛出一个异常,其中包含一些有意义的错误信息—–特别是在这个案例中你依赖于用户的输入。让findAction()方法抛出一个异常而不是简单的产生一个没有任何解释的NullPointerException 要好得多。
try { ParserFactory.getParser().findAction(someInput).doSomething(); } catch(ActionNotFoundException anfe) { userConsole.err(anfe.getMessage()); }
或者你认为try/catch 的机制太丑了,你的action应该跟用户提供一个反馈而不是什么都不做:
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); } } }