I am using a third party HTTP client to make GET, POST calls. I don't want to tie my code to this library. So I've decided to create an interface called HttpClient and an implementation of it called HttpClientImpl.
One of the methods in the interface is:
Response get(String url);
The Response object being returned from the interface is the object from the third party library. So this technically does not decouple my code from the third party library.
What is the best approach to decouple myself? Should I create my own response object that can wrap the response of the third party library?
This is a classic case of the Mediator design pattern:
The class which uses the HTTP client shouldn't be exposed to neither the HTTP client implementation (which you've already encapsulated) nor its response object.
Using generics here will not prevent the using class from knowing the response class in this case.
As you suggested - have a wrapping response class / have a converter from the 3rd party response to one of your own.
Instead of abstracting the http library, have you considered abstracting the repositories you are accessing through Http? Say for example, you have the restful endpoints for Tweets:
GET https://someapi.com/Tweets
GET https://someapi.com/Tweets/{id}
POST https://someapi.com/Tweets
PUT https://someapi.com/Tweets/{id}
DELETE https://someapi.com/Tweets/{id}
It would make sense to have a TweetRepository class, which can create, read, update and delete tweets. The interface for this class might look something like the following:
public interface TweetRepository {
public List<Tweet> get();
public int add(Tweet tweet);
public void remove(int id);
public Tweet get(int id);
public void update(int id, Tweet tweet);
}
If your controllers use the interface, then you can make your implementation use whatever http library you want without introducing coupling.
Related
I created a Java library for a REST service using Retrofit (https://square.github.io/retrofit/).
I have an Interface which looks like this:
public interface OrganizationUnitsApi {
#GET("organizationUnits")
Call<List<OrganizationUnit>> getOrganizationUnits();
#GET("organizationUnits/{organizationUnitId}")
Call<OrganizationUnit> getOrganizationUnit(#Path("organizationUnitId") String organizationUnitId);
}
As you can see, both times I resolve to the endpoint "organizationUnits", so my requests in the end will be sent to "https://myservice.com/organizationUnits..."
Is there a possibility in Retrofit to like "annotate" a base Url for this Interface?
Maybe something like this?
#Path("organizationUnits")
public interface OrganizationUnitsApi {
#GET("/")
Call<List<OrganizationUnit>> getOrganizationUnits();
#GET("{organizationUnitId}")
Call<OrganizationUnit> getOrganizationUnit(#Path("organizationUnitId") String organizationUnitId);
}
There is no such API at this moment in retrofit similar to what you are exactly trying to do. However, if you must need to do that, you can pass the organizationUnits as part of the baseUrl while building the retorfit object.
So now you are doing something like this
Retrofit.Builder().baseUrl(someUrl)
You can instead do something like the following
Retrofit.Builder().baseUrl(someUrl/organizationUnitId)
But in that case, if you are using the same base url for multiple API interface, you will have to do extra hassle to configure those separately.
Similar question was posted here Clean code - how to design this class?
I still don't find an answer though, I'm confused!
I read the book "clean code" too.He is saying in some part you shouldn't mix data structure/Object, whether data structure with no behaviour or an object with behaviour.
In my application we have Data tranfer objects which carry data from external services .These DTO have just data accessors and mutators. So I was considering them as Data structure type.
However Robert Martin is saying in his book that client.isMarried() is better than isMarried(client) I found this logical as isMarried function use attributes only from client class.. it is cleaner.
In many areas in my application we need some behaviour on a certain DTOs I'm confused where to put this behaviour.
We have made Utils classes that has business logic like
ClientUtils {
boolean isMarried(Client client) { ...}
String getCompleteName(Client client) { ...}
}
Should this go to the service layer ? even if these methods does not manipulate any thing else other than the input object It does not interact with another layer (DAL, services .. )
Since you can't change the Client class due to the external library constraint, I wouldn't extend it. I suggest making a ClientInfo wrapper class that "has a" Client member instead.
class ClientInfo {
private Client myClient;
public ClientInfo(Client c) {
myClient = c;
}
public boolean isMarried() { ...}
public String getCompleteName() { ...}
}
If you ask me, then Utils class just means you have a random static method lingering somewhere which contains actual business logic. Why not keep DTOs as DTOs, and create a ClientManager class that has isMarried method?
The ClientInfo approach that wraps the external object is another option, possibly driven by Domain Driven Security.
Assume that we've some interface my.gwt.shared.Facade in shared package of our GWT project (exists both server and client) and two implementation of it: class my.gwt.client.ClientFacadeImpl (exists only client) and class my.gwt.server.ServerFacadeImpl (exists only server).
Is there any way to write a piece of code or annotation that substitute ClientFacadeImpl in client side and ServerFacadeImpl in server side?
Thanks all for the answers and discussion. I've found simple and elegant solution for my needs.
So, I've interface my.gwt.shared.Facade and two classes: class my.gwt.client.ClientFacadeImpl and class my.gwt.server.ServerFacadeImpl.
interface Facade {
Map<Boolean, Facade> FACADES = new HashMap<Boolean, Facade>();
}
Now, we should fill you FACADES interface. This is done like that:
public class MyEntry implements EntryPoint {
static {
Facade.FACADES.put(true, ClientFacadeImpl.INSTANCE); // client side
}
And
#Startup
#Singleton
public class Initializer {
#PostConstruct
private void init() {
Facade.FACADES.put(false, ServerFacadeImpl.INSTANCE); // server side
// other things
}
}
Now, when I need to get appropriate Facade, I just write
Facade facade = Facade.FACADES.get(GWT.isClient());
Also in this case in map is only corresponding to server or client side implementation.
P. S. Goal of this question was to allow handling of some GwtEvents fired on client direclty on server and vice-versa. This solution removed large set of DTO (data transfer objects) and simplified code a lot.
There's no answer to your question other than "it depends". Or rather, of course there are ways of doing what you ask, but would you accept the tradeoffs?
Given that you tagged the question with dependency-injection, let's start with that. If you use a DI tool with GWT, it's likely GIN (Dagger 2 would work, but it's still under development). In that case, just use distinct modules for GIN client-side and Guice server-side that bind() the appropriate implementation.
For a few releases, GWT.create() can be made to work outside a GWT (client) environment (i.e. on the server side). You have to register a ClassInstantiator on the ServerGwtBridge as an alternative to the rebind rules from gwt;xml files. So you could have a <replace-with class="my.gwt.client.ClientFacadeImpl"> rule in your gwt.xml, and a ClassInstantiator returning a ServerFacadeImpl on the server side.
Finally, you can also use a static factory and replace it with a client-side specific version by way of <super-source>.
A last one, but I'm unsure whether it'd work: you could use an if/else using GWT.isClient(), and annotate your ServerFacadeImpl with #GwtIncompatible to tell the GWT compiler that you know it's not client-compatible.
At the moment I have to query database that I do not own which has a web service, so what they provide is what I get. Since this is in house (sort of), I might be able to get direct access in the future so that I can get better data in my query.
I don't want to have to write everything again and again. If I did this in Java would I write an Interface (programming kind, think Implements Interface, OOP)? How would I do this? Or do I just write a whole new class and "plug it in."
This is just a regular client/server architecture. Http request, server calls the servlet or jsp, returns data.
I'm not sure if my idea is correct design or not.
Definitely sounds like you should use an interface with different implementations here. Something like:
public interface DataAccess {
Data getData();
}
Then you can code against this API and just plugin/inject a different implementation as needed. So you could have this:
public class DirectDataAccess implements DataAccess {
public Data getData() {
//use JDBC, ORM, or similar
}
}
Or this:
public class WebServiceDataAccess implements DataAccess {
public Data getData() {
//call web service
}
}
But as long as your client code only references the DataAccess interface, then you have successfully decoupled your client from your service.
As I get more into RESTful APIs, the (good) simplicity of the approach means that you generate a LOT of boilerplate code, and code that has to match in three or four different places, e.g. for a Jersey-based stack:
HTML on the web page which provides controls (a button Create Foo)
JS on the web page which formulates the JSON and the request to create a Foo
A FooRest class method to handle the request and create a Foo
A Foo class to instantiate, which will manipulate the data structure
Are there tools which provide a starting point for some or all of this code automatically, possibly starting from something straightforward like a JSON data structure? E.g., provide:
card: {
methods: [GET],
}
handOfCards: {
methods: [GET POST PUT DELETE],
}
and at the very least end up with Ajax requests, CardRest and HandOfCardsRest classes with the specified methods stubbed out, and Card and HandOfCards classes with properties or getters/setters?
Have you tried Backbone.js? It is a JavaScript library that handles REST Ajax requests for you. It allows you to define your models to wrap the data and provides setters, getters, save and delete functions, etc.
It also allows you to bind the models to views which generate the UI HTML.
I think nearly any *rails application does all of this for you. Grails is my favorite right now, and once you get the initial setup done (a single command) you create domain classes with another command.
Once those are created, you can generate both views (html) and controllers for handling all of these actions with a single command, and the boiler plate is sufficient for a lot of initial sites. It will even create test cases for you, although you'll need to define what the actual tests do. You can program it by convention very easily, or create your own mappings from URLs -> controller actions. It has a ton of plugin support and easily handles remote submission of forms (via javascript) built in.
It doesn't take a json data structures for creation, but the domains are very easily created (using groovy) and it autowires getter/setters, service injections, etc as it is based on the Spring Framework.
Your goal should probably not be code generation of boilerplate but actually writing less code.
Spark is a Java micro web framework based on Sinatra.
Here's some example code:
import static spark.Spark.*;
import spark.*;
public class HelloWorld {
public static void main(String[] args) {
get(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. Show something ..
}
});
post(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. Create something ..
}
});
put(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. Update something ..
}
});
delete(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. annihilate something ..
}
});
options(new Route("/") {
#Override
public Object handle(Request request, Response response) {
// .. appease something ..
}
});
}
}
An alternate (or addition) to Juan's answer, you might want to check out Knockback.js , which takes the best of Knockout and adds the best of Backbone.js . Backbone has support for RESTful API's via it's "sync" functions. Quoting their website:
The method signature of Backbone.sync is sync(method, model,
[options])
method – the CRUD method ("create", "read", "update", or "delete")
model – the model to be saved (or collection to be read)
options – success and error callbacks, and all other jQuery request options
You might want to try a different approach altogether and try somethink like project lombok. It will at least let you nix all your getters and setters.