In my service class I would like to connect to external API. Where and how should I do it?
1) Inject in constructor ExternalClass and assign to private property. Next in other property in constructor call connect.
public MyClass(ExternalApi externalApi) {
this.externalApi = externalApi;
this.ExternalApiConnect externalApiConnect = externalApi.connect;
}
public void firstMethod() {
externalApiConnect.first();
}
public void secondMethod() {
externalApiConnect.second();
}
2) Outside constructor, so if I build dependencies in DI, then I don't call connection to external service.
private ExternalApiConnect externalApiConnect;
public MyClass(ExternalApi externalApi) {
this.externalApi = externalApi;
}
public void firstMethod() {
if (externalApiConnect == null) {
externalApiConnect = externalApi.getConnect();
}
externalApiConnect.first();
}
public void secondMethod() {
if (externalApiConnect == null) {
externalApiConnect = externalApi.getConnect();
}
externalApiConnect.second();
}
But now I have two repetitions and I have state in my service class. I don't think the state should be in service class?
How is the best way for this?
Edit:
3)
public MyClass(ExternalApi externalApi) {
this.externalApi = externalApi;
}
public void firstMethod() {
externalApi.getConnect().first();
}
public void secondMethod() {
externalApi.getConnect().second();
}