Java init method

Posted by Johan Sjöberg on Stack Overflow See other posts from Stack Overflow or by Johan Sjöberg
Published on 2012-11-02T10:55:52Z Indexed on 2012/11/02 11:00 UTC
Read the original article Hit count: 237

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.

© Stack Overflow or respective owner

Related posts about java

Related posts about design