I am trying to write a client library that will use HttpClient for sending and receiving information to/from a web server. At the core of this library will be a WebClient class:
public class WebClient {
public String send(String apiUrl) {
// Use HttpClient to send a message to 'apiUrl', such as:
// http://example.com?a=1&response=xml
//
// Wait for a response, and extract the HTTP response's body out
// as raw text string. Return the body as a string.
}
}
Now again, this is a library I am writing (mylib.jar). A library that consists of various distinct services, where each service has 1+ methods that an API developer can use for reading/writing data to the server. So services like:
WidgetService
getAllWidgets
getMostExpensiveWidget
getLastWidgetUpdated
etc...
FizzService
getFizzById
getFizziestFizz
etc...
BuzzService
etc...
...
Each service method will take 1+ Java primitives or 1+ model instances (entities, value objects, etc.). Every service method will return one such model object. So for instance:
public class FizzService {
public Fizz getFizzById(Long fizzId) {
// ...
}
public Fizz getFizzByBuzz(Buzz buzz) {
// ...
}
}
This is important to note because this means that the HTTP response body received by WebClient#send() ultimately needs to be mapped back to a Java object.
From the API developer’s perspective, I just want developers to instantiate each service instance, passing it a WebClient to use under the hood, and then have the service do all the mapping between arguments and api urls, and between HTTP response bodies and models/entities.
So for instance:
public class FizzService {
private WebClient webClient;
private FizzApiBuilder fizzApiBuilder;
// Getters & setters for all properties...
public Fizz getFizzByBuzz(Buzz buzz) {
// apiCall == "http://example.com/fizz-service/getFizzByBuzz?buzz_id=93ud94i49&response=json"
String apiCall = fizzApiBuilder.build(buzz).toString();
// We asked API to send back a Fizz as JSON, so responseBody is a JSON String representing
// the correct Fizz.
String responseBody = webClient.send(apiCall);
if(apiCall.contains("json"))
return JsonFizzMapper.toFizz(reponseBody);
else
return XmlFizzMapper.toFizz(responseBody);
}
}
// What the API developer writes:
WebClient webClient = WebClientFactory.newWebClient();
FizzService fizzSvc = new FizzService(webClient);
Buzz b = getBuzz();
Fizz f = fizzSvc.getFizzByBuzz(b);
So far I like this setup. However, I will need the same “boilerplate” code for every service method, across all services:
String apiCall = someBuilder.build(...)
String responseBody = webClient.send(apiCall)
if(apiCall.contains("json"))
return JsonMapper.toSomething(responseBody)
else
return XmlMapper.toSomething(responseBody)
This is starting to smell like a prime use case for abstraction. Ideally, I’d like to have all this boilerplate code in an AbstractService, and have each service extend that abstract class. Only one problem:
public abstract class AbstractService {
private WebClient webClient;
private ServiceApiBuilder apiBuilder;
// Getters & setters for all properties...
public Object invoke(Object... params) {
// apiCall == "http://example.com/fizz-service/getFizzByBuzz?buzz_id=93ud94i49&response=json"
// The injected apiBuilder knows how to validate params and use them to build the api url.
String apiCall = apiBuilder.build(params).toString();
String responseBody = webClient.send(apiCall);
if(apiCall.contains("json"))
return jsonMapper.to???(reponseBody);
else
return xmlMapper.to???(responseBody);
}
}
public class FizzService extends AbstractService { ... }
The problem is that abstracting the functionality out to an AbstractService makes things awkward for building the API call (but not impossible), but worse, I have absolutely no idea how to create and inject a set of JSON/XML mappers that will know what model/entity to map the responseBody back to.
All this is starting to stink. When my code stinks I look for solutions, and if I can’t find any, I come here. So I ask: am I taking a fundamentally wrong approach, and if so, what should my approach be? And if I’m close, then how do I inject the correct mappers and get this code smelling better? Keep in mind my code snippet showing how I want the API developer to actually use the models/services – that’s the ultimate goal here. Thanks in advance.
As touched upon in the comments, we know both the kind of request we want to make and the type of response at compile-time, so I wouldn’t have the code work these things out at runtime simply so that it can be extracted into a base class. You have to write extra code for it to make those decisions, which just leaves room for subtle bugs. Also, having the API builder to work out what call to make based purely on the parameters will paint you into a corner; e.g.
getMostExpensiveWidgetandgetLastWidgetUpdatedboth sound like parameterless methods, so how is the API builder class going to know what to do?Therefore, assume that we will give the API builder classes separate methods for different API calls. Also assume that the methods on the mapper classes are not static. Then the
getFizzByBuzzmethod could look like this:Similarly, the
getFizzByIdmethod could look like this:Both these methods follow the same pattern, and they differ by a specific API builder method (e.g.
buildForBuzzvsbuildForId) and a specific response mapper (jsonFizzMappervsxmlFizzMapper), since we don’t want to make those decisions at runtime. Therefore the only real redundancy is the call to the web client. Assuming thatJsonFizzMapperandXmlFizzMapperimplement someFizzMapperinterface, my next step would be to make the following private method in theFizzServiceclass:getFizzByBuzzandgetFizzByIdcan now look like this:I think that this is a good balance between purity and pragmatism. Ideally you would just pass the sendRequest method a builder method (e.g.
buildForBuzz), but the hoops you would have to jump through in terms of interfaces and anonymous classes don’t seem worth it.If you wanted to go further you could make the sendRequest method generic and then put it into an abstract base class (or preferably favour composition over inheritance and put it in a completely separate class), and then you would need to make your mapper interfaces generic. However since that class would just contain a two-line method, that would smell to me that it probably isn’t worth it. Therefore I think creating a corresponding private method for each service class should be fine, but extract the functionality elsewhere if you think it’s likely that it will get more complex.