What happens when a constructor partially succeeds before throwing an exception?

Suppose I have the following base class:

public class RootClass { private List<RootClass> children = new ArrayList<RootClass>(); public RootClass(RootClass parent) { if (parent != null) { parent.addChild(this); } } public void addChild(RootClass child) { children.add(child); } } 

And I have the following child class:

 public class ChildClass extends RootClass { public ChildClass(RootClass parent) { super(parent); doInitialization(); } private void doInitialization() { //Might throw an unchecked exception } } 

Now suppose I create an instance of ChildClass that throws an exception, but falls outside the scope of the constructor (somewhere deep in the code, so far away, it does not know that ChildClass has not been completely built). Now the parent has a link in his children list to the ChildClass , which did not have its own constructor.

How to deal with these situations? Is this just a bad design scheme? Or does it make the least sense? I really don't want to reorganize the whole application to add a parent to a parent after the constructor completes.

+4
source share
2 answers

As a general principle, you should avoid leaking the 'this' value from constructors at all costs. In this case, the parent will have a link to the semi-constructed object. It should be encoded in the caller, e.g. parent.addChild (new Child ()) instead of automatically adding.

+2
source

If this:

  private List<RootClass> children = new ArrayList<RootClass>(); 

There was a static field, you would simply skip the semi-initialized object into the wild. Like not, it just won't make any difference.

You only have a problem if this link runs somewhere outside the object, then you will have a partially initialized object waiting for problems to occur on your system. As long as you make sure that the link does not lose its temper, everything is fine.

+1
source

All Articles