【发布时间】:2012-12-28 04:50:34
【问题描述】:
在这里使用什么模式比较好?
我不想返回空值,这感觉不对。
另一件事是,如果我想返回导致它为空的原因怎么办?如果调用者知道它为什么为空,它可以做一些额外的事情,所以我希望调用者知道它并以这种方式行事
Public CustomerDetails getCustomerDetails(){
if(noCustomer){
..log..etc..
return null;
}
if(some other bad weird condition){
..log..etc..
return null;
}
CustomerDetails details= getCustomerDetailsFromSomewhere();
if (details!=null){
return details;
}
else {
..log..etc..
return null;
}
}
【问题讨论】:
-
为什么你认为返回 null 不好??有什么具体原因吗?
-
一种可能性是,您可以抛出
IllegalArgumentException。或者创建您自己的 CustomException,并使用它。但是,相信我,这将花费您更多的时间而不是返回 null。现在为什么你不想返回 null? -
@GanGnaMStYleOverFlowErroR 每次我必须调用它时我都会进行一次空检查,因此很容易出错,但主要原因是在这种情况下它只是“感觉”错误。我可能错了
标签: java design-patterns optimization