开发者

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

开发者 https://www.devze.com 2023-03-24 13:59 出处:网络
Suppose I have the following base class: public class RootClass { private List<开发者_运维知识库RootClass> children = new ArrayList<RootClass>();

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 a ChildClass that throws the exception, but is caught outside the constructor (somewhere in the depths of the code, so far away, it doesn't know that the ChildClass has not been fully constructed). Now the parent has a reference in its children list to the ChildClass which has not had its constructor run.

How should these situations be handled? Is this just a bad design scheme? Or does this make the least bit of sense? I don't really want to refactor the entire application to add the child to the parent after the constructor finishes.


As a general principle, leaking the value of 'this' out of constructors is to be avoided at all costs. In this case the parent object will have a reference to a half-constructed object. It should be coded in the caller as e.g. parent.addChild(new Child()) rather than have the add be automatic.


If this:

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

Was a static field, you would just have leaked a half-initialized object into the wild. As it is not, it just won't make any difference.

You only have an issue if this reference leaks to somewhere out of the object, then you would have a half-initialized object waiting to cause issues on your system. As long as you make sure the reference does not go anywhere out of itself, it's all good.

0

精彩评论

暂无评论...
验证码 换一张
取 消