Home > front end >  Null Object Pattern in a self-referencing type
Null Object Pattern in a self-referencing type

Time:11-28

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?

CodePudding user response:

If you only use one class you need nulltype but you can use a interface for the start.

    public class Node : NodeRoot {
        public string Data { get; init; }
        public Node? Parent { get; init; }
        public List<Node> Children { get; init; } = new();

        private Node(string data) {
            Data = data;
        }

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

        public static Node Factory(string data, Node parent) => new(data, parent);

        public static INodeRoot Factory(string data) => new Node(data);
    }

    public interface INodeRoot {
        public string Data { get; }
        public List<Node> Children { get; }
    }

CodePudding user response:

You could keep the field non nullable but force null into it by using the syntax = null! (note the ! which tells the compiler to trust you). I would probably combine this technique with a subclass and/or static instance to be used as the root parent, and prevent issues when accessing that null parent field (or add a computed field isRoot).

  • Related