原文链接 Avoiding != null statements
在StackOverFlow上,看到了对判空语句的讨论。
Best votes 的答题者认为 初、中级程序员喜欢在方法中返回null,因此在调用这些方法中不得不去判空。这样,在他们潜意识中为了保护自己的代码就会加入大量的判空语句,这是不好的。
程序中出现null有如下两种情况:
- null是一个有意义的返回值 (比如在方法中返回null,作为一种情况的标示)
- null是一个异常
对于第二种情况,Best votes 的答题者给出如下两种解决方法:
- assert语句,可以将设定的错误原因放到assert的参数中,这样当程序异常时,可以返回错误且程序不会往下走。( 在开发中使用assert不推荐,更多的应该用在unit test 中。参照Java陷阱之assert关键字 )
- 抛出空指针异常
对于第一种情况,就是通过返回空对象替代返回null.
1 对于数组或集合,应该返回零长度的数组或集合
//The right way to return an array from a collection
private final List<Cheese> cheesesInStock = ...;
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];
public Cheese[] getCheeses(){
return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}
//The right way to return a copy of a collection
public List<Cheese> getCheeseList(){
if(cheesesInStock.isEmpty())
return Collections.emptyList();
else
return new ArrayList<Cheese>(cheesesInStock);
}
2 对于返回类型不是数组或集合,那就返回空对象。实例如下:
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();
}
精简写法(空对象模式):
ParserFactory.getParser().findAction(someInput).doSomething();