jeudi 12 mai 2022

What is the best practice to construct an object depending of external calls?

I am trying to build an object that gets its data from external APIs. I will try to explain it with an example:

First of all, I get a POST body in my API to create an object:

class CarRequestBody {
    private String colorId;
    private String engineId;
    //Constructors, etc.
}

Then with this info I need to build a detailed instance of the Car. Feeding the data from external services:

ColorDetails color = colorApiClient.getColor(colorId);
EngineSpecifications engine = engineApiClient.getEngine(engineId);

And finally I build my Domain Object with all this info.

So i would like to know what is the best practice in order to build the instance. I have thought in 3 different ways:

1 - A method in CarService like this:

public Car createCar(CartRequestBody body) {
    ColorDetails color = colorApiClient.getColor(body.getColorId);
    EngineSpecifications engine = engineApiClient.getEngine(body.getEngineId);
    Car car = new Car(color, engine);
} 

2 - Feed the data in the constructor:

public Car(CarRequestBody body) {
    this.color = colorApiClient.getColor(body.getColorId);
    this.engine = engineApiClient.getEngine(body.getEngineId);
}

3 - In the getters of the domain class:

class Car {
    private ColorData color;
    private EngineSpecifications engine;
    //Constructor

    public ColorData getColor() {
        if (color == null){
            return colorApiClient.getColor(colorId);
        }
        return this.color;
    }
    ....
}

Is there some design patter for this scenario?

Aucun commentaire:

Enregistrer un commentaire