返回null坏设计? [英] Is returning null bad design?
问题描述
伪代码:
变量x = object.method()
如果(x为空)做某事
不返回null的理由是,您不需要检查它,因此您的代码不需要根据返回值遵循不同的路径 。您可能需要查看空对象模式,其中提供了有关此信息的更多信息。
例如,如果我要在Java中定义一个返回一个Collection的方法,我通常会喜欢返回一个空集合(即 Collections.emptyList()
)而不是null,因为这意味着我的客户端代码更干净;例如
集合<?项目> c = getItems(); //永远不会返回null。
for(项目项目:c){//如果c为空,则不会进入循环。
//处理项目。
}
...比以前更清洁:
集合<?项目> c = getItems(); //可能返回null。
//两个可能的代码路径现在更难测试。
if(c!= null){
for(项目项目:c){
//进程项目。
}
}
I've heard some voices saying that checking for a returned null value from methods is bad design. I would like to hear some reasons for this.
pseudocode:
variable x = object.method()
if (x is null) do something
The rationale behind not returning null is that you do not have to check for it and hence your code does not need to follow a different path based on the return value. You might want to check out the Null Object Pattern which provides more information on this.
For example, if I were to define a method in Java that returned a Collection I would typically prefer to return an empty collection (i.e. Collections.emptyList()
) rather than null as it means my client code is cleaner; e.g.
Collection<? extends Item> c = getItems(); // Will never return null.
for (Item item : c) { // Will not enter the loop if c is empty.
// Process item.
}
... which is cleaner than:
Collection<? extends Item> c = getItems(); // Could potentially return null.
// Two possible code paths now so harder to test.
if (c != null) {
for (Item item : c) {
// Process item.
}
}
这篇关于返回null坏设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!