problem description
there has always been a doubt, that is, is it better to encapsulate a request into an object for management, or to call this interface directly?
for example:
for example, we have an interface to request a data
void requestData (int param, Callback callback);
scenario 1:
Click the button, request data, and display data
then it is generally easy to use it directly.
onClick(View v) {
requestData(123, new Callback() {
onCallback(String data) {
someTextView.setText(data);
}
});
}
scenario 2:
if an interface, you can make a request and initiate it multiple times. Because the parameters are different, the data will be different. For example, a calendar interface, request No. 1 and request No. 3 are all possible, because the data will be different at different times.
at this time, I find it easier to manage by encapsulating it into an object.
class RequestDataSession implements Callback{
void start(int time) {
requestData(time, this);
}
onCallback(String data) {
// do things.
}
}
onDateSelect(int time) {
RequestDataSession rds = new RequestDataSession();
rds.start(time);
}
in the case above, each request is independent and easy to manage.
I find it easier to manage encapsulated objects, because I can track whether each request is in the request and isReuqesting, can also implement multiple requests with different parameters such as scenario 2.
scenario 1 is actually a special case of scenario 2.
but recently I have encountered some requirements and found that it is better to use the method to directly call the chained way of writing.
is to call request B when request A comes back, and request B then call request C. In this way, if I encapsulate it into an object to operate, it is difficult to disassemble it, and it is difficult to add a process to it.
but it is more convenient if the method is called directly.
requestA(new CallbackA() {
onA() {
requestB(new CallbackB() {
onB() {
requestC(xxxx);
};
});
}
})
would like to hear your thoughts and discuss this problem of writing