Is this initialization safe?

Life44 :

I have a class like that:

public class WorkHelper {

    private final Worker worker;

    public WorkHelper(Worker worker) {
        this.worker = worker;
    }

    //...

}

and everybody knows that the initialization below is wrong:

public class Worker {

    private final WorkHelper helper;
    private final SomeClass some;

    public Worker(SomeClass some) {
        helper = new WorkHelper(this);
        this.some = some;
    }

}

But how about the one below? Is this correct?

public class Worker {

    private final WorkHelper helper = new WorkHelper(this);
    private final SomeClass some;

    public Worker(SomeClass some) {
        this.some = some;
    }

}
Bohemian :

All versions are unsafe; they are all cases of “letting this escape”.

Consider creating a factory method that creates the worker helper after construction is complete, for example:

public class Worker {

    private WorkHelper helper;
    private SomeClass some;

    // hide the constructor
    private Worker() {}

    public static Worker create(SomeClass some) {
        Worker worker = new Worker();
        worker.some = some;
        worker.helper = new WorkHelper(worker); // pass post construction
        return worker;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=25307&siteId=1