0

I have 2 different requests that have the same parameters and response handling, but it depends on one flag if the app should use on or the other API.

Everything works just fine but I have a question about simplifying the Main.java.

I tried to use java.lang.reflect.Method but to no avail. What are the other options to simplify this?

MyRestApi.java

public interface MyRestApi {
   @POST("first")
   Call<Void> firstRequest(@Header(AUTH) String authorization, @Body String body);     

   @POST("second")
   Call<Void> secondRequest(@Header(AUTH) String authorization, @Body String body); 
}

Main.java

JobService.ApiRequestor apirequestor;
MyRestApi restApi;

if(true) {
    apiRequestor.request(restApi.firstRequest(auth, body), res -> {
        doStuff(res);
    });
} else {
    apiRequestor.request(restApi.secondRequest(auth, body), res -> {
        doStuff(res);
    });
}
Richard
  • 1,087
  • 18
  • 52
  • If both requests are the same parameter-wise, then why not just using two instance of Retrofit with different configurations? In fact I'm pretty sure most parameters can be passed down to the call itself so you might only need one instance. – breakline Jun 11 '21 at 12:20
  • But the call itself is to 2 different APIs, or am i misunderstanding the answer? – Richard Jun 11 '21 at 12:26
  • Clean Code, [page 41](https://books.google.co.uk/books?id=_i6bDeoCQzsC&pg=PA41&dq=%22It+does+one+thing+if+the+flag+is+true+and+another+if+the+flag+is+false!%22&hl=en&newbks=1&newbks_redir=1&sa=X&ved=2ahUKEwjT5r358o_xAhXh5eAKHTc1CREQ6AEwAXoECAsQAg): "Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!" – Boris Jun 11 '21 at 15:31
  • If the "two different API's" only differ in an url, then those are not "two different API's", just different configurations basically. And Retrofit does support multiple configurations. However if ONLY the base url differs then Retrofit is able to use absolute URL's therefore you can pass down the whole url as an argument. – breakline Jun 13 '21 at 07:32

0 Answers0