L
L
l4m3r2019-03-13 13:07:57
OOP
l4m3r, 2019-03-13 13:07:57

Does a binary node inherit the interface of a non-binary node?

Wrote the basic node interface.

interface NodeInterface
{
    public function key();
    public function value();
    public function __construct($key, $value);
    public function contains(NodeInterface $node): bool;
    public function addChild(NodeInterface $node);
    public function setParent(NodeInterface $node);
    public function parent(): ?NodeInterface;
    public function children(): array;
    // ...
}

By implementing the Node class based on it, we get a typical node with many children. OK.
But here, let's say, you need to write a binary node class for a binary tree.
There can be only 2 subnodes: left, right. How to implement?
  1. Inherit from Node and set hard limits:
    interface BinaryNodeInterface extends NodeInterface
    {
        public function left(): ?BinaryNodeInterface;
        public function right(): ?BinaryNodeInterface;
    }
    
    class BinaryNode extends Node implements BinaryNodeInterface
    {
        public function left(): ?BinaryNodeInterface
        {
            return $this->children[0] ?? null;
        }
    
        public function right(): ?BinaryNodeInterface
        {
            return $this->children[1] ?? null;
        }
    
        public function addChild(NodeInterface $node)
        {
            if (count($this->children) < 2) {
                parent::addChild($node);
            }
        }
    }

    But then the substitution principle from SOLID is grossly violated.

  2. Make two different basic interfaces like MultiNodeInterface and BinaryNodeInterface, but then you get code duplication and is not universal.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question