我正在遍历Exchange Web Services Java API代码,并看到了开发人员将参数传递给他们的方法的一种设计选择。请您帮忙解释一下这项技术的好处-

该方法要处理的类型在传递给该方法之前由Generic Wrapper类包装,例如,如果该方法要在String上工作,则将新Param()传递给其中Param定义为的方法跟随

class Param<T> {
  private T param;
  public T getParam() { return param; }
  public void setParam(T param) { this.param = param }
}

这是源代码段-该方法适用于HttpWebRequest对象。
调用者创建Param的实例,即以HttpWebRequest类为边界。然后将该实例传递到方法中,如您在方法签名中所看到的那样:
protected HttpWebRequest emit(OutParam<HttpWebRequest> request)
throws Exception {
   request.setParam(this.getService().prepareHttpWebRequest());
   OutputStream urlOutStream = request.getParam().getOutputStream();
   EwsServiceXmlWriter writer = new EwsServiceXmlWriter(this.service,urlOutStream);
   this.writeToXml(writer);
   urlOutStream.flush();
   urlOutStream.close();
   writer.dispose();

   request.getParam().executeRequest();
   if(request.getParam().getResponseCode() >= 400)
   {
      throw new Exception("The remote server returned an error:("+request.getParam().getResponseCode()+")"+request.getParam().getResponseText());
    }
    return request.getParam();
}

那为什么不仅仅传递HttpWebRequest对象-
开发人员在整个代码库中重复使用此模式,这使我认为这样做有充分的理由。但我只是看不到好处...请赐教。

最佳答案

在方法入口处,包装的HttpWebRequest实例应为null。这是一种通过return语句以外的其他方式返回实例的方法,即使在方法调用过程中出现了问题(例如,如果抛出异常)。这种模式在某种程度上等效于C#中的关键字out。它也可以用来返回一个对象+一个错误状态:

bool getGreetings(OutParam<Greetings> greetings) {
  if (aCondition) {
     greetings.setParam(new Greetings("Hello");
     return true; // everything's fine
   }
   return false;
}

而不是写:
Greetings getGreetings() {
  if (aCondition) {
     return new Greetings("Hello");
  }
  return null; // caller will have to test a null condition to know it the operation was ok
}

10-07 19:22
查看更多