Spr*_*ing 7 java optimization design-patterns
在这里使用什么样的好模式?
我不想返回空值,这感觉不对.
另一件事是,如果我想返回导致它为null的原因怎么办?如果调用者知道它为什么是null,它可以做一些额外的事情,所以我希望调用者知道它并以这种方式行事
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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的意思是null不能解释其状态,您可以CustomerDetails使用另一个可以提供更多详细信息的类进行包装。例如:
class Feedback()
{
private CustomerDetails result;
private int status;
public static final int STATUS_OK = 0;
public static final int STATUS_NULL = 1;
public static final int STATUS_NO_CUSTOMER = 2;
public static final int STATUS_BAD_CONDITION = 3;
public Feedback(CustomerDetails result, int status)
{
this.result = result;
this.status= status;
}
public CustomerDetails getResult(){return result;}
public int getStatus(){return status;}
}
Run Code Online (Sandbox Code Playgroud)
并改变你的方法:
Public Feedback getCustomerDetails()
{
if(noCustomer)
{
..log..etc..
return new Feedback(null, Feeback.STATUS_NO_CUSTOMER);
}
if(some other bad weird condition)
{
..log..etc..
return new Feedback(null, Feeback.STATUS_BAD_CONDITION);
}
CustomerDetails details = getCustomerDetailsFromSomewhere();
if(details != null)
{
return new Feedback(details, Feeback.STATUS_OK);
}
else
{
..log..etc..
return new Feedback(null, Feeback.STATUS_NULL);
}
}
Run Code Online (Sandbox Code Playgroud)
然后您可以通过 获取状态feedback.getStatus()。