简体   繁体   中英

Best practice for initializing an object that requires network calls Java

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM