Reputation: 49197
What's a good way to make sure an init method is invoked in java? The alternatives I see are
NullPointerException
public void foo() {
if (!inited) {
throw new IllegalArgumentException("not initalized");
}
...
}
public void foo() {
if (!inited) {
throw new IllegalArgumentException("not initalized");
}
fooInternal();
}
private void fooInternal(){ ... };
public void foo() {
init();
...
}
public void init() {
if(!inited) {
...
}
}
public void foo() {
if (!inited) {
init();
}
...
}
Most of these approaches are very verbose and decreases overall readability.
Upvotes: 2
Views: 8831
Reputation: 4867
If initialisation is part of the usage contract throw IllegalStateException
because the client of the class has not caused it to transition to the correct "initialised" state…
Whether you initialise upon creation or not depends on how it is to be used. For instance if a possibility is that it may be used by a Spring ApplicationContext then you'll want to defer initialisation.
Upvotes: 5
Reputation: 80194
Most of the time you want to fail fast so choose the mechanism that helps you fail fast based upon the container your application is executing in. For e.g if a web container then may be you initialize it during creation of servlet context. Moreover, I am not sure why the below is verbose. It is simple, clear and explicit on the intent.
public void foo() {
if (!inited) {
init();
}
...
}
Upvotes: 2
Reputation: 37833
Call init();
whithin an initializer block, that way every constructor call will also execute init();
.
Upvotes: 2