tags:

views:

193

answers:

6

Let's say I have a Java class

abstract class Base {
    abstract void init();
    ...
}

and I know every derived class will have to call init() after it's constructed. I could, of course, simply call it in the derived classes' constructors:

class Derived1 extends Base {
    Derived1() {
        ...
        init();
    }
}

class Derived2 extends Base {
    Derived2() {
        ...
        init();
    }
}

but this breaks "don't repeat yourself" principle rather badly (and there are going to be many subclasses of Base). Of course, the init() call can't go into the Base() constructor, since it would be executed too early.

Any ideas how to bypass this problem? I would be quite happy to see a Scala solution, too.

UPDATE: Here is a generic version of the Factory Method approach:

interface Maker<T extends Base> {
    T make();
}

class Base {
    ...
    static <T extends Base> Maker<T> makerWithInit(Maker<T> maker) {
        T result = maker.make();
        result.init();
        return result;
    }
}

UPDATE 2: This question is basically "how do you use Template Method for constructors"? And the answer seems to be, "You can, but it's a bad idea". So I can do a Template Factory (Template Method + Abstract Factory) instead.

+7  A: 

Avoid this. If you do it, any class that extends your DerivedX class may decide to also call init() thus leaving the object in inconsistent state.

One approach is to let the init() method be invoked manually by clients of your class. Have an initialized field, and throw IllegalStateExcepion if any method that requires initialization is called without it.

A better approach would be to use a static factory method instead of constructors:

public Derived2 extends Base {
    public static Derived2 create() {
       Derived2 instance = new Dervied2();
       instance.init();
       return instance;
    }
}

Update: As you suggest in your update, you can pass Builder to a static factory method, which will call the init() on the instance. If your subclasses are few, I think this is an overcomplication, though.

Bozho
This still leaves me with calling `init()` separately in the factory method for `Derived1`, `Derived2`, etc.
Alexey Romanov
yes, your builder version is a good addition.
Bozho
Re your last sentence, from the question: "(and there are going to be many subclasses of Base)".
Alexey Romanov
+3  A: 

In addition to Bozho's recommendation, an application container is excellent for the task.

Mark your init() method with the javax.annotation.PostConstruct annotation and a rightly configured EJB or Spring container will execute the method after the dependency injections are finished, but before the object can be used by the application.

An example method:

@PostConstruct
public void init() { 
    // logic..
}

In an enterprise application you can open resources to for example the files system in the init() method. This initialization can throw exceptions and should not be called from a constructor.

Espen
+6  A: 

What happens in init()? It's likely that a better design could eliminate the method altogether, or at least relax the requirement that it execute after the sub-class' constructor. Be certain that init() does not make the object under construction visible to any other threads before the constructor completes, because that creates concurrency bugs.

As an (ugly) alternative, an abstract method could be implemented by sub-classes as a pseudo-constructor:

abstract class Base {
  Base() {
    ctor();
    init();
  }
  abstract void ctor();
  abstract void init();
}
erickson
Actually, this looks better than other solutions to me (ugly, but less ugly than alternatives).
Alexey Romanov
+1  A: 

Or use spring... you can do <beans default-init-method="init">, see Default initialization and destroy methods.

Istao
+1  A: 

If you are adverse to using factories for some reason, you could use the following trick:

trait RunInit {
    def init():Unit
    init()
}

class Derived1 extends Base with RunInit {
    def init() = println("INIT'ing!")
}

This will run init() before the Derived1 constructor/body.

Fred Haslam
The problem is precisely that I want `init` to run _after_ the `Derived1` constructor/body.
Alexey Romanov
A: 

if Java had it, we wouldn't see all these init() method calls in the wild.

"surround child constructor with something" - that cannot be done in pure java. Too bad, because there can be very interesting applications, especially with anonymous class + instance initialization block.

factory and container - they can be helpful when native new doesn't do the job; but that's trivial and boring, and won't work with anonymous classes.

irreputable