Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A curious way of passing a parameter to a method

I was going through the Exchange Web Services Java API code and saw a design choice in the way the developers passed arguments to their methods. May you can help explain the benefits of the technique --

The type that is to be processed by the method is wrapped by a Generic Wrapper class before being passed into the method, for example if the method is to work on a String, new Param() is passed into the method where Param is defined as follows

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

Here is a snippet from the source -- The method works on an HttpWebRequest object.
The caller creates an instance of the Param, i.e. bounded by the HttpWebRequest class. Then that instance is passed into the method, as you can see in the method signature --

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();
}

Then why not just pass the HttpWebRequest object -- The developers use this pattern repeatedly all over the code base which makes me think there is some good reason for it. But I just can't see the benefit... please enlighten.

like image 898
bell0 Avatar asked Jun 19 '12 20:06

bell0


1 Answers

At the method entrance, the wrapped HttpWebRequest instance is expected to be null. This is a way to return the instance by an other mean than the return statement, even if something goes wrong during the method call (if an exception is thrown for instance). This pattern is somehow equivalent to the keyword out in C#. It could be also used to return an object + an error status :

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

rather than writing :

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
}
like image 74
Yanflea Avatar answered Nov 07 '22 00:11

Yanflea