Reputation: 29806
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
Reputation: 1381
To some extent it's a matter of taste. To me it's fine so long as:
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
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
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