Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java init method

What's a good way to make sure an init method is invoked in java? The alternatives I see are

  • Don't test it, let the method fail by itself, likely by a NullPointerException
  • Test if method was initialized or throw
public void foo() {
     if (!inited) {
         throw new IllegalArgumentException("not initalized");
     }
     ...
}
  • Delagate
public void foo() {
     if (!inited) {
         throw new IllegalArgumentException("not initalized");
     }
     fooInternal();
}

private void fooInternal(){ ... };
  • Always init, and make init a noop otherwise
public void foo() {
     init();
     ...
}
public void init() {
     if(!inited) {
         ...
     }
}
  • Silently init
public void foo() {
     if (!inited) {
         init();
     }
     ...
}

Most of these approaches are very verbose and decreases overall readability.

like image 345
Johan Sjöberg Avatar asked Jun 30 '26 04:06

Johan Sjöberg


1 Answers

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.

like image 183
robert Avatar answered Jul 01 '26 18:07

robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!