Why are circular references considered harmful? [c

2020-01-27 10:38发布

Why is it a bad design for an object to refer to another object that refers back to the first one?

标签: .net oop
11条回答
叼着烟拽天下
2楼-- · 2020-01-27 11:06

Because now they're really one single object. You can't test either one in isolation.

If you modify one, it's likely that you affect its companion as well.

查看更多
叛逆
3楼-- · 2020-01-27 11:10

Such an object can be difficult to be created and destroyed, because in order to do either non-atomicly you have to violate referential integrity to first create/destroy one, then the other (for example, your SQL database might balk at this). It might confuse your garbage collector. Perl 5, which uses simple reference counting for garbage collection, cannot (without help) so its a memory leak. If the two objects are of different classes now they are tightly coupled and cannot be separated. If you have a package manager to install those classes the circular dependency spreads to it. It must know to install both packages before testing them, which (speaking as a maintainer of a build system) is a PITA.

That said, these can all be overcome and its often necessary to have circular data. The real world is not made up of neat directed graphs. Many graphs, trees, hell, a double-linked list is circular.

查看更多
爷的心禁止访问
4楼-- · 2020-01-27 11:10

The .NET garbage collector can handle circular references so there is no fear of memory leaks for applications working on the .NET framework.

查看更多
\"骚年 ilove
5楼-- · 2020-01-27 11:12

It is completely normal to have objects with circular references e.g. in a domain model with bidirectional associations. An ORM with a properly written data access component can handle that.

查看更多
趁早两清
6楼-- · 2020-01-27 11:12

Refer to Lakos’s book, in C++ software design, cyclic physical dependency is undesirable. There are several reasons:

  • It makes them hard to test and impossible to reuse independently.
  • It makes them difficult for people to understand and maintain.
  • It will increase the link-time cost.
查看更多
登录 后发表回答