samedi 27 novembre 2021

Null Object Pattern in a self-referencing object

Suppose I have a class named Node, which represents a node in a hierarchical structure. For instance it could look something like this:

public class Node
{
  public readonly string Data { get; set; }
  public readonly Node Parent { get; set; }
  public readonly List<Node> Children { get; } = new()

  public Nome(string Data, Node parent)
  {
    Data = data;
    Parent = parent;
  }
}

Notice the property Parent is of type Node and it's non-nullable, so I cannot assign null to it. Now suppose I want to implement the Null Object Pattern for this class, for instance to create the root node.

I found myself in a chicken and egg situation because I cannot create a Node without having a node.

Are there any alternatives except making Parent nullable?

Aucun commentaire:

Enregistrer un commentaire