简体   繁体   中英

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?

Seriously consider not making the connection bidirectional. I don't know what the particular scenario is, but in my experience you can usually recast your problem so that it's based on a directed graph instead.

If you then, still, occasionally need to walk the graph in the opposite direction, you can transpose it. All directed graphs can be transposed by reversing the arrows. Depending on the size of the graph this could be an expensive operation, but again depending on the actual usage scenario, there are often solutions to those problems as well. For instance, if you can make the graph immutable, you can use memoisation to deal with performance problems.

Bidirectional connections in code tends to cause all sorts of trouble, so it's well worth the effort to look for alternatives. I can't recall when was the last time I designed a system with bidirectional connections, but I guess that it's more than a decade ago.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM