Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Static Initialization Good Programming Practice?

In Java, we use the static initialization block:

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.

like image 909
Tapas Bose Avatar asked Feb 19 '12 09:02

Tapas Bose


People also ask

Is static variable initialization necessary?

Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block.

Are static blocks bad Java?

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.

When would you use a static initialization block?

The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. Note: We use Initializer Block in Java if we want to execute a fragment of code for every object which is seen widely in enterprising industries in development.

How many static initializers can you have?

There can be multiple static initialization blocks in a class that is called in the order they appear in the program.


2 Answers

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. 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.

like image 128
JB Nizet Avatar answered Oct 06 '22 00:10

JB Nizet


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;
like image 44
Peter Lawrey Avatar answered Oct 06 '22 00:10

Peter Lawrey