mercredi 20 janvier 2021

C#: What's the best way to ensure that two functions (2 different classes) never get called independently of each other?

For example I have classes Branch and Node. My code expects a bi-directional connection between them, so I must call:

branch.addNode(node);
node.addBranch(branch);

to connect them. I don't want branch.addNode() to be ever called without the corresponding node.addBranch(). What's the best way to achieve that?

I can probably make Node.addBranch() protected and make Branch inherit Node and just call from Branch class:

// Branch class
public void addNode(Node node)
{
    this.myNodeList.add(node);
    node.addBranch(this);
}

but to me it looks like a hack. Is there a better way?

Aucun commentaire:

Enregistrer un commentaire