I would like to have the following method which returns HttpResponse. But at the same time I do not want to initialize HttpResponse to null.
Which is a good way to do, adding throws for the method or adding try/catch blocks with HttpResponse initialized to null.
HttpResponse is an interface so initializing this doesn’t make any sense.
I am thiking of adding getters/setters for HttpResponse declaring this as a member variable.
Ideas are appreciated.
public HttpResponse executeRestClientServiceCall(final HttpUriRequest request)
{
// Verifier;
HttpResponse httpResponse = null;
final HttpClient client = new DefaultHttpClient();
try
{
httpResponse = client.execute(request);
return httpResponse;
}
catch (final ClientProtocolException e)
{
}
catch (final IOException e)
{
}
return httpResponse;
}
You should not catch the exception at this point. Not at all. This makes your code much simpler. What you have to do though is to release all the resources that you used, and do so properly. This is the code to do that:
At this point you cannot decide what to do with the exception, so the best choice is to just let it slip through to the caller. Maybe he knows what to do with it.
Throwing an exception gives the caller more possibilities than just returning
null.Considering your other questions:
This is good, since you can write your code so that the variable always holds a proper object. See the code above.
I answered it above. The good way is to add a
throwsclause for the method.Don’t do that. The
HttpResponseis an object that typically has a very short life span. It should always be stored in a local variable, and when the method returns, there is no need to keep it. This is different from theHttpClient, which you should store in a field of a class, so you can add a connection pool later if you need it.