1

I have an object called Datastore, for example, that requires a few variables to initialize: value1, value2, and a key. The two values are arbitrary, but the key must be validated by means of a call to an API over the network, how should initialization of this object be set up? Is it okay to have network calls inside of the constructor? Should setters be used with a no args constructor? Builder pattern?

Example key validation

private int verifyKey(String key) { 
    try {
        URL url = new URL("https://api.com/verifykey/" + key);
        HttpUrlConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connection();
        //other implementation
   } catch(Exception e) {
        e.printStackTrace();
   } finally {
        //close connection
   }
   //return result
}
1
  • 1
    I would construct the Key separately and then feed it to the Datastore constructor.
    – user207421
    Jun 26, 2020 at 0:46

1 Answer 1

2

In most of the case i think the code inside the constructor should be as simple as possible. Firstly because this will be more easy to test it and because this will let your code more easy to use.

You should also take a look to the IoC pattern Who explain why you should not initialize other object in constructor. (or at least avoid it)

And using setters only for create an object is not a good idea because the arg of the constructor will let you define what is the minimum you need for using this object.

Also if you want to easily make asynchronous call and do some stuff during the network call finish you can try to use java.util.concurrent.Future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.