Tapas Bose
Tapas Bose

Reputation: 29806

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

Thanks in advance.

Upvotes: 13

Views: 8125

Answers (3)

Tim Gage
Tim Gage

Reputation: 1381

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.

Of course if your application is a 10 line single-class experiment then this matters a whole lot less.

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.

Upvotes: 9

Peter Lawrey
Peter Lawrey

Reputation: 533530

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;

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691765

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.

Upvotes: 5

Related Questions