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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.