Java – a strange way to pass parameters to methods
I was browsing the Java API code for exchange web services and saw the design choices of the methods developers passed parameters to them You can help explain the benefits of this technology –
Before passing to the method, the type processed by the method is wrapped by the generic wrapper class. For example, if the method is processing string, pass the new param() to the method defined as param as follows
class Param<T> { private T param; public T getparam() { return param; } public void setParam(T param) { this.param = param } }
This is a snippet of source code – this method applies to the Httpwebrequest object The caller creates an instance of param, which is qualified by the Httpwebrequest class The instance is then passed to the method, as shown 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(); }
So why not pass the Httpwebrequest object directly - developers use this pattern repeatedly throughout the code base, which makes me think it has some good reasons But I just don't see the benefits... Please advise
Solution
At the method entry, the wrapped Httpwebrequest instance should be null This is a method that returns an instance in a way other than a return statement, even if there is a problem during the method call (for example, if an exception is thrown) This pattern is equivalent to the keyword out in C # to some extent It can also be used to return the error status of an object:
bool getGreetings(OutParam<Greetings> greetings) { if (aCondition) { greetings.setParam(new Greetings("Hello"); return true; // everything's fine } return false; }
Instead of 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 }