oop - 最佳实践 : Adding child node to a parent in child constructor or not?

标签 oop

我正在处理一些代码,在子节点的构造函数中将子节点添加到它的父节点。代码如下所示:

类(class):

class Node1 {
  public Node1(Node1 parent, String name) {
     if(parent != null) {
       parent.add(this);
     }
     this.parent = parent;
  }

  private void add(Node1 child) {
    children.add(child);
  }
}

用法:
Node1 parent = new Node1(null, "parent");
Node1 child1 = new Node1(parent, "child1");
Node1 child2 = new Node1(parent, "child2");

通过以这种方式实现它,类 Node1 的用户不必显式地将子节点(更少的代码)添加到它的父节点,并且你已经保证子节点有一个父节点。

我个人不会这样写,但更像是以下内容:
class Node2 {
  public Node2(String name) {
  }

  public void add(Node2 child) {
    children.add(child);
    child.setParent(this);
  }
}

Node2 parent = new Node2("parent");
Node2 child1 = new Node2("child1");
parent.add(child1);
Node2 child2 = new Node2("child2");
parent.add(child2);

所以我的问题是,如 Class Node1 中所示实现它是一个好主意吗?或者有人反对这样做吗?或者没有争论为什么一个比另一个更好?

最佳答案

我个人不喜欢第一个示例,因为您正在添加一个尚未“准备好”的节点(因为构造函数没有完成执行)。在大多数情况下,它可以正常工作,但在极端情况下,您可能会遇到很难找到的错误。

关于oop - 最佳实践 : Adding child node to a parent in child constructor or not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/629926/

相关文章:

php - 在静态函数中访问公共(public)/私有(private)函数?

c++ - 处理包含动态分配成员的对象的 vector

c++ - 如何强制实现者做某事

PHP 5.3 : Late static binding doesn't work for properties when defined in parent class while missing in child class

php - 如何使一个类的实例成为另一个类的实例

c++ - 为什么这些类不完整?

java - 如何检查元素是否是类列表中元素的子类

javascript - 在 jquery 代码块中使用时出现 'this' 问题

c# - C#中的Delphi类

c++ - 为什么基类枚举不被继承?