13

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.

2
  • 1
    I will comment because there is no "black or white" answer to your question. Personally, I do not find the static accessor a good friend of programmers. Dependency injection is a very nice alternative that also helps a lot when it comes about testing. Commented Feb 19, 2012 at 9:33
  • 1
    I have seen a code where new threads are started in the static block. :) It was very bad. Commented Feb 19, 2012 at 9:39

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

3

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.