Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good or Bad - Use a constructor to initialize model from a remote webservice

I would like know if it good or bad to initialize my model by a request to a webservices or is it better to use an another public method called after the constructor

For example:

class Model {
    ModelData data;

    Model(Integer model_id) {
       data = Request.getDataFromWebServices(model_id);
    }
}
like image 765
sahid Avatar asked Jun 25 '11 21:06

sahid


1 Answers

It is generally a good aproach to use as constructor args parameters that are required for the class to be functional (instead of using setters).
So in your case if model_id is mandatory for Model to work, it is correct you have it there.
Now you use model_id to do a remote method call.
Remote method calls can take more time to execute, making Model taking more time to initialize and could fail e.g. due to network reasons.
If the api covers any exception either coming from network layer or from the actual processing and returning a good value to initialize the Model then IMHO it should be ok as it is.
Just document the class as taking more time to initialize due to network access

like image 82
Cratylus Avatar answered Sep 20 '22 23:09

Cratylus