I am writing a Java library that needs to make http GET && POST requests. There will be two types of users of this library:
- Those with understanding of callbacks and know how to use them.
- Those that....don't.
So please consider the following two methods:
public void methodWithCallback(ServiceCallback callback) {
try {
// GET && POST code that cannot really be abstracted to a separate method
} catch (IOException e) {
callback.onError(e);
callback = null;
}
callback.onSuccess(response);
callback = null;
}
public Response methodWithoutCallback() throws IOException {
try {
// again, GET && POST code that cannot really be abstracted to a separate method
} catch (IOException e) {
logger.log(e);
throw e;
}
return response;
}
Above code seems dirty to me, mainly because it has duplication of code to send the request. Also if I were writing a lot of such kind of methods, my code will very soon double up to hardly maintainable spaghetti.
I considered allowing the client to set a callback by providing a method like setCallback(Callback callback)
, and then have one general method
that notifies the callback if it is NOT null. But this also seems dirty because I would be then writing a lot of if null
checks!
What are your thoughts on it? What would be the desirable design pattern here that you would recommend?
Aucun commentaire:
Enregistrer un commentaire