简体   繁体   English

初始化需要网络调用 Java 的 object 的最佳实践

[英]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.例如,我有一个名为 Datastore 的 object,它需要一些变量来初始化:value1、value2 和一个键。 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?这两个值是任意的,但密钥必须通过网络调用 API 来验证,应该如何设置这个 object 的初始化? 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.您还应该查看IoC 模式Who解释为什么您不应该在构造函数中初始化其他 object。 (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.并且仅使用 setter 来创建 object 并不是一个好主意,因为构造函数的 arg 将让您定义使用此 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此外,如果您想轻松进行异步调用并在网络调用完成期间做一些事情,您可以尝试使用java.util.concurrent.Future

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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