简体   繁体   English

静态初始化是良好的编程实践吗?

[英]Is Static Initialization Good Programming Practice?

In Java, we use the static initialization block: 在Java中,我们使用静态初始化块:

private static final ApiKey API_KEY;

static {
    API_KEY = new ApiKey();
}

I was wondering that 我在想这个

  • Is it a good programming practice? 这是一个很好的编程习惯吗?
  • Where should we use this pattern? 我们应该在哪里使用这种模式?

Thanks in advance. 提前致谢。

To some extent it's a matter of taste. 在某种程度上,这是一个品味问题。 To me it's fine so long as: 对我而言,只要:

  • You keep the field final, as you have done 正如你所做的那样,你保持最终的领域
  • You make sure the object referenced is immutable and thread-safe 您确保引用的对象是不可变的并且是线程安全的

Statics tend to make writing good tests harder. 静态倾向于使编写好的测试变得更难。 If you ever find you want to start modifying static state then you probably need to look at the design again. 如果您发现想要开始修改静态,那么您可能需要再次查看设计。

Consider looking at Google Guice and its very nice Singleton implementation . 考虑一下Google Guice及其非常好的Singleton实现

Of course if your application is a 10 line single-class experiment then this matters a whole lot less. 当然,如果您的应用程序是10行单级实验,那么这个问题要少得多。

Note that in your example, you could simplify to: 请注意,在您的示例中,您可以简化为:

private static final ApiKey API_KEY = new ApiKey();

That's not always possible though. 但这并不总是可行的。 Perhaps you have omitted some more complex initialization code? 也许你省略了一些更复杂的初始化代码? In which case Guice would again be worth a look. 在这种情况下,Guice再次值得一看。

You could avoid using a static initializer block completely by using the following code: 您可以使用以下代码完全避免使用静态初始化程序块:

private static final ApiKey API_KEY = new ApiKey();

or 要么

private static final ApiKey API_KEY = createNewApiKey();

if the API key creation requires more than just a constructor call. 如果API密钥创建需要的不仅仅是构造函数调用。 That makes the code more readable, IMHO. 这使得代码更具可读性,恕我直言。 But it doesn't matter much. 但这并不重要。

The static initializer is useful when two static fields depend on the same initialization code: 当两个静态字段依赖于相同的初始化代码时,静态初始化程序很有用:

static {
    // compute some values
    A = somePartOfTheComputedValues();
    B = someOtherPartOfTheComputedValues();
}

But even then, A and B could perhaps be refactored into a single object, which would be created in a single method. 但即便如此,A和B也许可以重构为单个对象,它将在单个方法中创建。

I like using enums whenever possible. 我喜欢尽可能使用枚举。

Instead of 代替

class ApiKey {        
    private static final ApiKey API_KEY;

    static {
        API_KEY = new ApiKey();
    }

I would write 我会写的

enum ApiKey {
    INSTANCE;

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

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